i was wondering what the difference is when u put a variable in another variable with the notation. So i have a variable "Body" and in there is HTML tags, text and PHP variables, ive found out i can put them in between hooks but that they would react exactly the same. Example:
In this piece of code the variable is in between { } hooks.
$body = "
<table style='border: 1px;'>
<tr>
<td><b>Naam:</b></td><td>{$naam}</td><br>
</tr>
</table>"
And here it is not.
$body = "
<table style='border: 1px;'>
<tr>
<td><b>Naam:</b></td><td>$naam</td><br>
</tr>
</table>"
And this both reacts exactly the same. So can anyone tell me if this has an actual use, or that this is just like all PHP with the 10 ways to do the same thing.
Thanks in advance.
Addition
This is not a duplicate ofThis. It does not explain the part of why a variable inside of a variable can be put in between curly brackets.
Usage of curly braces inside " is particularly useful when you want to add complex instruction or access object/array properties.
This code will perfectly work
<?php echo "Test {$foo['bar']}"; ?>
<?php echo "Test {$foo->bar}"; ?>
While this one will fail
<?php echo "Test $foo['bar']"; ?>
<?php echo "Test $foo->bar"; ?>
So yes, it's not particularly useful if you are accessing a simple variable, but when you want to play with array and object, it's useful.
Related
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I know is a stupid question but well i am trying so hard but i can't figure out on where i am missing the comma i am totally confused ,The below code is giving me an error.
it would be great if someone can help me out with a referencing on comma and tips / Tricks on them :)
i tried replacing the commas in different places but still it didn't worked out.
<td><?php echo <a href="test1.php?id=<?php echo $row['ID'];?>"/>Download! ?></a></td>
Thanks :)
It has to be:
<td>
<?php
echo 'Download!';
?>
</td>
Alternatively:
<td>
Download!
</td>
<td><a href="test1.php?id=<?php echo $row['ID'];?>"/>Download!</a></td>
Try this one
One important thing to remember is that you do not have to use echo to output static HTML content, only for the dynamic part, the variable in you case. The correct version looks like:
<td><a href="test1.php?id=<?php echo $row['ID'];?>"/>Download!</a></td>
The immediate approach typically would be that:
<td>Download!</td>
Often it can be shortened, depending on your php configuration:
<td>Download!</td>
To me the second form is more readable, thus my personal preference.
There is one redundant echo with opening/closing php tags, also you wrongly self-close the a tag.
In your html template it is sufficient to write:
<td>
Download!
</td>
Code between <?php and ?> is php code which is "injected" in html.
$row is array and with $row['ID'] you get value of specific key from array which is ID. You can access the value on this key also with double quotes like $row["ID"] there is no difference, because you want to access the key which is referenced by string with value ID. You can embrace string with single or double quotes.
More on strings in php manual: http://php.net/manual/en/language.types.string.php
When you want to use same quotes in string you have to escape it like
<?php
echo "This is double quote: \"."; //result: This is double quote: ".
?>
same with single quote:
<?php
echo 'This is single quote: \'.'; //result: This is single quote: '.
?>
You can echo some other string with value from array for example:
<?php echo "this row has id: " . $row["ID"]; ?>
so you concatenate string and value with the period/dot.
Or you can access value of variable in string like:
<?php
$rowId = 1;
echo "this row has id: $rowId"; //result: this row has id: 1
?>
But it is hard to spot it and many IDE's will not highlight it. Better can be to concatenate it with period (echo "this row has id: " . $rowId;).
You can also specify value from array, but you have to enclose it with {} so the php engine know that it is array variable no the literal
<?php echo "this row has id: {$row["ID"]}"; ?>
or object property:
<?php echo "this row has id: {$row->id}"; ?>
But it can also be hard to spot it when you write it like this.
When you want to literally write all this code you can enclose it by single quotes:
<?php
echo '<?php echo "this row has id: {$row["ID"]}"; ?>'; //result: <?php echo "this row has id: {$row["ID"]}"; ?>
?>
or escape all double quotes and dollar sign $ and the result will be same:
<?php
echo "<?php echo \"this row has id: {\$row[\"ID\"]}\"; ?>";
?>
I'm trying to modify a bit of PHP code to get it to assign a unique CSS class to the elements it creates as it cycles through its loop. Theoretically, I'm just trying to take a "name" that's echoed to the screen and assign that as a class to a element that's created next... Here's the intitial relevant code loop:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Simplistcally, I'm trying to get the string that's echoed by $exam->name to be assigned to the class of that <tr> element. Something like
<tr class="<?php echo $exam->name;"><td><?php echo $exam->name;?></td></tr>
Although I'm sure I'm handling the quotes or syntax improperly (at least, anyway, it doesn't end up assigning the class to the <tr>.
It will help if you stop going in and out of PHP so much, it will probably be easier to read this way:
<?php
foreach($my_exams as $exam){
if($exam->is_taken){
echo '<tr class="'.$exam->name.'"><td>'.$exam->name.'</td></tr>';
}
}
If you want to do double quotes, you need to escape them when you want to echo them, but then you can use a variable without concatenating a bunch of strings. (Once you are using objects/arrays it helps to surround each variable with {})
echo "<tr class=\"{$exam->name}\"><td>{$exam->name}</td></tr>";
Reference: http://us2.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
<tr class="<? echo $exam->name ?>"><td><? echo $exam->name ?></td></tr>
Others have answered this pretty much the same way I am about to, but I want to add this to explain the issue. And why this is not a “stupid” question, but more of a bizarre byproduct of the way that some CMS system mix HTML & PHP within their templates. In short: They format the template as nice HTML to make it seem clean & easy for non-coders, but in doing so their mixing of inline-PHP makes PHP coding seem more difficult than it is. Meaning this code:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Can easily be this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo '<tr><td>'
. $exam->name
. '</td></tr>'
;
}
}
?>
Which is now easier to parse from a programming standpoint, so you can now do this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo sprintf('<tr%s><td>', ' class="' . $exam->name . '"')
. $exam->name
. '</td></tr>'
;
}
}
?>
What I did there is use sprintf to place ' class="' . $exam->name . '"' into the ''. The %s means that is a string that should be placed there, and the string is what comes after the comma in the sprintf statement. I find this much easier to code, test & debug. But in general, the key to making PHP coding easier is to just use straight PHP when any logic needs to be placed in the context of HTML.
So I got the following: I'm creating dynamic pages (based on the page ID (obtained through $_GET)). My page consists of a $_get check (the html may only be shown if a $_GET variable is set) and the echo'ing of a page with html tags + php variables. Things like:
<table>
<tr>
<td>Name:</td>
<td>myFunction('foo');</td>
</tr>
</table>
etc etc etc.
I include this code above myincludedfile.php into my main file with functions include and isset($_get) .
echo include 'myincludedfile.php';
This, however, not seems to work. Altough the html gets shown, the variables and functions remain text and don't get executed.
Can anyone help me out?
Change it like this:
<table>
<tr>
<td>Name:</td>
<td><?=myFunction('foo');?></td>
</tr>
</table>
That way you are actually opening a small PHP block in the template. <?= is a shorthand notation for <?php echo, although it depends on your server configuration if the shorthand is enabled.
If the function doesn't return a value, but echos it instead, you can leave out the = as well and just execute the function like this: <? myFunction('foo'); ?> or the long notation: <?php myFunction('foo'); ?>.
In general, you don't need <?php at the start of your file. It's just that everything inside <?php .. ?> tags is executed as php and the rest is considered static output.
B.t.w. you don't need to use echo when you include a file.
Here is another alternative
$myfunction = myFunction('foo');
echo <<<CODE
<table>
<tr>
<td>Name:</td>
<td>$myFunction</td>
</tr>
</table>
CODE;
include 'myincludedfile.php';
This is called the heardoc syntax http://php.net/manual/en/language.types.string.php#example-75
You will have to include the file like this:
include 'myincludedfile.php';
What you are doing, is echo'ing the php file
Look:
<?php
$html="<h1>Hello</h1>";
function hello()
{
echo "<h1>Hello</h1>";
}
function hello2()
{
?>
<h1>Hello</h1>
<?php
}
?>
All these does the same thing.
to use them, you can do the following:
<?php
hello(); // Hello
hello2(); // Hello
echo $html; // Hello
?>
I don't think i get what you need, but try to be more specefic.
The code below is a sample code of the top oh my php web page. There are php variables being outputted in specific places.
I'd to implement an HTML to PDF converter, but it requires me to put all of my code into a single variable that the PDF converter will use in its class. How can I put my existing into into a single variable say: $html without having to open up all my PHP variables, escpaing everything and concatenating the whole place? I was thinking of using heredocsyntax but it doesn't like the <?php ?> and I'm sort of confused as I've never used it in the past. Any ideas on how to achieve this?
Ideally, this is what I'd like to do:
$html = <<<EOD
<div id="topHeaderView"><?php echo configuration::getValue(6); ?></div>
<table>
<tr>
<td><?php echo $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]; ?></td>
</tr>
EOD;
The above doesn't capture any values outputted by $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"] or by configuration::getValue(6).
Insead of:
$html = "";
$html .= "<div id=\"topHeaderView\">".configuration::getValue(6)."</div>";
$html .= "<table>";
$html .= "<tr>";
$html .= "<td>".$lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]."</td>";
$html .= "</tr>";
This is something I want to avoid...
This is a good use of output buffering
ob_start();
?><div id="topHeaderView"><?php echo configuration::getValue(6); ?></div>
<table>
<tr>
<td><?php echo $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]; ?></td>
</tr>
<?php
$html = ob_get_clean();
As far as I can see in the manual, it is not possible to call functions inside HEREDOC. A less cumbersome solution is:
$config_print = configuration::getValue(6);
$lang_print = $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"];
$html = <<<EOD
<div id="topHeaderView">$config_print</div>
<table>
<tr>
<td>$lang_print</td>
</tr>
EOD;
Edit: Or you could use:
$html = <<<EOD
<div id="topHeaderView"><?= _( configuration::getValue(6) ); ?></div>
<table>
<tr>
<td><?= _( $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"] ); ?></td>
</tr>
EOD;
heredoc is php syntax therefore it needs to be inside the php tags. The php documentation, here, explains the behavior of variables within heredoc strings:
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped... Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
There are also some examples in the documentation.
<?php
$value = configuration::getValue(6);
$header = $lang["FAI_R"]["PRT"]["TITLE"]["HEADER"];
$html = <<<EOD
<div id="topHeaderView">$value</div>
<table>
<tr>
<td>$header</td>
</tr>
EOD;
?>
The manual has a whole chapter devoted to the assorted string syntaxes that PHP provides (4 to date). You're basically missing string interpolation:
$html = <<<EOD
<div id="topHeaderView">$value</div>
<table>
<tr>
<td>{$lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]}</td>
</tr>
EOD;
Fiddle
However, it isn't as simple as that. You are using PHP to generate code in another language (HTML) and you need to ensure that the resulting code is valid. Thus you cannot inject random stuff. In order to insert literal text inside HTML you need to use htmspecialchars(). And variable interpolation expects, well, variables, not functions. So the heredoc syntax offers little advantage here. Concatenation would be a simpler alternative:
$html = '<div id="topHeaderView">' . htmlspecialchars($value) . '</div>
<table>
<tr>
<td>' . htmlspecialchars($lang["FAI_R"]["PRT"]["TITLE"]["HEADER"]) . '</td>
</tr>';
You said you don't to escape and concatenate. I understand you. That's why complex HTML generation normally relies on template engines. Find one or build your own.
I have to modify some parts of a large PHP application. The different parts were written, of course, by different people (mostly interns). After looking through the code, I found that there were 2 styles of coding used by the other developers:
The 'PHP is the glue of the Internet' style, mixing html and php, ex.:
[snip]
<tr class="ds_subsubhead_2">
<td colspan="21" align="left"> A <select name="nb_linge" onChange="MM_jumpMenu('parent',this,0)" style="vertical-align:middle"> <option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','9999') ?>" <? if($messagesParPage == '9999') { ?>selected="selected"<? } ?>>Tous</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','25') ?>" <? if($messagesParPage =='25') { ?>selected="selected"<? } ?>>25</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','50') ?>" <? if($messagesParPage =='50') { ?>selected="selected"<? } ?>>50</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','75') ?>" <? if($messagesParPage =='75') { ?>selected="selected"<? } ?>>75</option>
[snip] or
<td <? if((isset($_GET['t1']))&&($_GET['t2']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
<td <? if((isset($_GET['t3']))&&($_GET['t4']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
<td <? if((isset($_GET['t5']))&&($_GET['t6']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
[snip] or even
<script type="text/javascript" src="<?=$_SESSION["path"]?>lib/js/ajax.js"></script>
[snip]
... and the more procedural way, ex.:
[snip]
$output .= '<td valign="top"><form name="form5" method="GET" action=""><select name="m" onchange="this.form.submit()">';
if ( empty($_GET['p']) ) $output .= '<option value=" ">All</option>';
else $output .= '<option value='.$_GET['m'].'>'.$_GET['m'].'</option>';
$query = "SELECT DISTINCT maoie FROM ".$BD."site";
$res = mysql_query($query);
while ( $row = mysql_fetch_assoc($res) ) {
if( !empty($row['maoie']) ) $output .= '<option value="'.$row['maoie'].'">'.$row['maoie'].'</option>';
}
$output .= '</select></form></td>';
$output .= add_more_stuff();
echo $output;
Now, I'm not completely sure that this is a more procedural way to do things, but at least it is different from the previous one. Which one, do you think, is generally better?
I, personally, dont't like 'the glue of the Internet' style.
I would ditch both and code the PHP away from any presentation-layer specific HTML. Otherwise things get very nasty, very quickly for anything bigger than 'Hello World' :)
You are shooting yourself in the foot if you want to modify the code later. I would try and kill off this problem by porting to a proper CMS/Abstract presentation.
Neither look good. I wouldn't want to maintain code in either style. save time later by spending time now cleaning it up properly.
Even something as basic as moving your HTML into externally loaded format strings and running them through sprintf() or similar might be better than the current situation. And you say you have a mix of these coding styles !?!
good luck to you sir!
Both styles should be relegated to the tomb of dynamic internet growing pains. Take a peek through some open source PHP projects to see a good, maintainable coding style in action. Things like http://sourceforge.net/projects/wikipedia MediaWiki show a good mix of HTML-In-Source and separation (although it is not perfect IMHO)
There is a third option: templates. Templates are more readable than glue or random emission of ascii vomit. I just tend to use HEREDOCd strings and str_replace, thus:
$template = <<<TEMPLATE
<html>
<head>
<title>{TITLE}</title>
</head>
<body>
<div id='nav'>{NAV}</div>
<div id='content'>{CONTENT}</div>
</body>
TEMPLATE;
$data = array (
"{TITLE}" => "Page title example",
"{NAV}" => buildNav(),
"{CONTENT}" => buildContent());
str_replace(array_keys($data),array_values($data), $template);
I tend to go for something in the middle. If I'm calling fifteen different functions to generate a select <option>, why not just have one function that does everything and creates the complete markup?
Something like this (completely made up example):
<select>
<?php
foreach (database_query() as $row)
echo gen_select($row)
?>
</select>
and somewhere else
function gen_select($row) {
// do something horrifically complicated with the data (creating some variables to make the output easier to follow
return "<option class=\"$class\">$text</option>";
}
I personally work on a CMS that has the latter version, and I am having a very hard time reading it.
2ndly, model/controller code within view's is a great Italian dish.
Both are horrible (that's the real weakness of PHP in my opinion), but at least the first looks readable.
Problems will eventually arise once conditions (is the request POST? is the data valid?) are added, and it will lead invariably to the dreaded second kind of coding. Try to decouple view and logic: str_replacing is way better than building a string by concatenating one gazillion small pieces.
No offence, but both style is from the late '90-s.
You should seriously consider refactor the system and use a template engine to separate at least the PHP and the HTML code.
Even better if you can separate the "business logic" and the "display logic" part.
I think HTML and PHP should be seperated as much as possible. It makes the whole code easier to read and creates a clear structure. That means for me that PHP should not output HTML, since you can use HTML to do that part...
So I'd also prefer the last example, but with one difference: I think using the bracket-style mixed into HTML makes it very hard to read the code. The if...endif style is the better alternative I think. Also printing HTML with PHP seems unlogic.
I'd do it this way:
<td valign="top"><form name="form5" method="GET" action=""><select name="m" onchange="this.form.submit()">;
<? if ( empty($_GET['p']) ): ?>
<option value=" ">All</option>
<? else: ?>
<option value="<?=$_GET['m']?>"><?=$_GET['m']?</option>
<? endif; ?>
<?
$query = "SELECT DISTINCT maoie FROM ".$BD."site";
$res = mysql_query($query);
while ( $row = mysql_fetch_assoc($res) ):
?>
<? if( !empty($row['maoie']) ): ?>
<option value="<?=$row['maoie']?>"><?=$row['maoie']?></option>
<? endif; ?>
<? endwhile; ?>
</select></form></td>
<? echo add_more_stuff(); ?>
At least this is a bit more logic. Nevertheless things like database interaction should be excluded to somewhere else in your web application. If you seperate the data and the design of your page it gets much clearer.
Nevertheless I think using PHP as a template language is totally fine as long as you only use some replacement variables and simple if-statements.