I can’t find answer anywhere or just don’t get it.
So, I have HTML and PHP code combined in my PHP file. In books it’s written that the code in <?php ?> are executed on server only and html will display in browser. But I don’t understand THIS:
<?php if ($a = $b) { ?>
<p>Text when condition is true</p>
<?php } else { ?>
<p>Text when condition is false</p>
<?php } ?>
The above is working in browser but I don’t understand why it doesn't output error
or at least it should output both sentences.
For me it seems that the statement is broken into peaces and the only way when it should work is:
<?php
if ($a = $b)
{
echo "<p>Text when condition is true</p>"
} else {
echo "<p>Text when condition is false</p>"
}
?>
What do I miss here?
It's just the way it works. PHP is a templating language and you can play tricks like that.
A piece of HTML in between two PHP blocks is interpreted as "output these characters".
It's generally a good idea to keep this kind of intermixing of PHP and HTML to a minimum, though - any serious back-end code that goes beyond simple if/else structures or loops should be in a separate location.
The former is useful when you need to output several html depending on the condition. Imagine you need to load a whole div with text. Doing with html is easier to handle. For small conditions like your example, the second example would make more sense.
Related
I do not like spitting back html with php's echo, makes it hard to do and read nested elements. So I usually write conditions that write raw html and make it as readable as possbile when editing the file directly or viewing the output html through the browser. However, I cannot find a style that stays readable for long. Any suggestions?
<?
if($foo == $bar)
{
?>
<div>
<p>hello, world</p>
</div>
<?
}
?>
As you can see, it doesn't look too good. At least not to me, but it makes the browser output more readable so I can better check the it for any mistakes.
i dont want this:
<?
if($foo == $bar)
{
echo "<div>\n\t<p>hello, world</p>\n</div>\n";
}
?>
Is my approach incorrect to begin with? should I use php to output to a .html file? and just view from the browser for mistakes and do as much php as possible inside the php file?
Your right it's not nice, instead use proper alternative syntax, for content with a large amount of HTML:
<?php if($foo == $bar): ?>
<div>
<p>hello, world</p>
</div>
<?php endif ?>
I don't believe you need a seperate template language to write maintainable code, PHP is perfectly fine in outputting variables in HTML.
Really the problem is seperating your logic from your output which a template engine can't help with if your not structuring your code properly in the first place. For example stuffing it all in an index.php file or not using MVC whereas you don't put HTML with your logic.
If you have a large project or are overly concerned with separating your PHP from your views, or you want the features which come with a template engine like built in caching and slots etc, then use one. But maybe first look at learning a framework which will improve your overall codebase as most frameworks come with their own. Though essentially you can achieve the same thing including nesting partials and blocks/slots with a 20 line view class which uses ob_* functions, which doesn't require you to learn a new syntax.
Rant over.. :s
Use a templating system like Smarty so you can separate your logic from your display code.It also allows you to bring in a designer that can work with html and might not know php at all. Smarty templates read more like HTML than PHP and that can make a big difference when dealing with a designer.
Ansered by #boatcoder
You can learn here
Without the use of templating engine, your best bet is #Lawrence's answer or this littly modified syntax of your first exemple (trimminig space and php tag) :
<? if($foo == $bar) { ?>
<div>
<p>hello, world</p>
</div>
<? } ?>
I was surprised to find that you can break out of a PHP function into raw HTML and back. I knew that you could do this sort of thing with loops and conditionals, but this was a surprise to me. Is it an accident or is this well-defined behavior? (I couldn't find any explicit discussion of the function case in the manual.)
[NOTE: The following code doesn't give a good example of when I would use this behavior, but I kept it simple for demonstration purposes.]
<?php
$i = 0;
while($i++ < 3) {
?><p>I am in a while loop.</p><?php
}
// this part surprised me
function actSkeptical($adjective) {
?><p>Is it <?= $adjective ?> that this works?.</p><?php
}
actSkeptical("weird");
?>
Output:
I am in a while loop.
I am in a while loop.
I am in a while loop.
Is it weird that this works?
I know some people absolutely hate mixing PHP and HTML like this, but I can't do OOP/templating (for reasons I won't go into here) and I do like seeing as much raw HTML as possible.
Also, I don't quite understand the semantics of how the short open/close tag above (outputting $adjective) works in conjunction with the surrounding code. Does PHP just treat raw HTML like it was an echo statement? And then the <?= $adjective ?> is just like including a variable within a string?
I can't seem to find any documentation relating to the exiting of PHP tags within blocks. However, there's really only a few places escaping to HTML will work.
Normal Usage
<?php
php_related_code();
?>
//html/css/js/etc
Within blocks, such as while, for, functions, etc
<?php
for ($i = 0; $i < 5; $i++) {
?>
hello world
<?php
}
$i = 5;
while ($i-- > 0) {
?> hello there <?php
}
function myFunc() {
?>
hello universe
<?php
}
myFunc();
You can think of ?>stuff<?php similar to an echo or print command found in PHP, because you can escape to HTML in the same places you can echo. So you can echo within the main script, in for loops, and you can echo in functions. But you can't echo in an array, for example:
<?php
$array = array(echo "here"); //not allowed
$array = array(?>here<?php); //also not allowed
So you can think of escaping the same as echoing in which it can tell you where you can use it, but you can't do the same thing when you're thinking about what it does.
They act differently and are processed by PHP differently as well. But your question is only asking about any restrictions so I won't go into what are the differences between ?><?php and echo.
I forgot to mention, <?=$variable?> is just short tag for <?php echo $variable; ?> if you have this feature enabled.
This is called a spaghetti code. DO NOT USE IT.
If you really want to separate code, logic and markup start using MVC; YII is great.
http://www.yiiframework.com/
Also check this out: https://www.youtube.com/watch?v=mhwfFgSzg7U
Okay, so I have a question. I use print <<< END followed by an END; after my html and variables instead of echo and print. I use this because it doesn't seem to have an effect on speed and the code just looks more organized in my opinion. I'm sure others will disagree but it's just my opinion.
I have a current project and that's the primary method I use to output HTML. No problems so far.
What are the disadvantages to using this? I have spoken with coders about it before, but they never really give me a reason not to use it just to not use it. I would appreciate any advice on this because I haven't had any problems with it.
The syntax you're describing is called a heredoc. As far as I know there is no performance difference between using heredocs and single- / double-quoted strings.
Heredocs can often help to prevent syntax errors, because there is no need to escape ' and " within the string. Another option would be to jump out of PHP into plain HTML, which requires no echo calls whatsoever:
<?php
... do things ...
?>
<div id="result"><?php var_dump($result); ?></div>
<?php
... do more things ...
?>
The only disadvantage i can think of is its harder to read for developers. This too is opinion but i find it much easier to read alternate syntax in template files, i.e.:
<?php if($something): ?>
<div id="something">
<?php echo $something->text ?>
</div>
<?php endif; ?>
And switching in and out like this is the only reason i can see to use heredoc as far as html is concerned. IF you have functions that are outputting massive amounts of html then you should change those to include a file in some manner. IE. you shoudl need to switch in and out of html except in your view, and those views should be separate completely form your functions or models. for exampl you should be doing:
function getSomething($var){
if($var){
$html = <<< HTML
<div id="something">
$var->text
</div>
HTML;
}
}
This is obvioulsy a simle example and actually this example isnt so bad, but if the HTML is more complex it starts to get jsut ugly. And in the case of methods on model classes its just plain evil no matter how simple the HTML is. Id prefer something like the following:
getSomething($var, $template = 'something.php')
{
if($var){
ob_start();
include($template); // $var is accessible in something.php
return ob_get_clean();
}
return null;
}
Of course the include will result in slight a performance hit but thats where caching comes in :-)
I make this PHP script, but Dreamweaver points (as parsing of the code written) that this string is Incorrect.
In any case it works perfectly, but maybe I'm wrong somethings :
for($i=1; $i<=$npagine; $i++) {
?> <a <? if($i==$index) { ?> class="paginas" <? } else { ?> class="pagine" <? } ?> href="index.php?<?=$splitter_zone?>&index=<?=$i?>"><?=$i?></a> <?
}
Any ideas?
The code looks okay. However, your code is very difficult to read - I can almost understand dreamweaver for choking on it :)
Here is a simpler suggestion:
for($i=1; $i<=$npagine; $i++)
{
$class = ($i == $index ? "paginas" : "pagine");
echo "<a class='$class' href='index.php?$splitter_zone&index=$i'>$i</a>";
}
Not sure, but you are using the short tag for php. And it's not supported on all installs like it use to be. short_open_tag must be on to use short tags.
<?php
// bla
?>
not
<?
//bla
?>
The first thing that's wrong with it is that you should be using <?php to open your PHP tags, not just <?. The short form has been deprecated, and may not always work correctly.
Additionally, the short form <?= to print the output is deprecated. You should be using <?php print or <?php echo. (Yes, I know it makes the code longer... don't grumble about it! ;-))
This is probably what's breaking your program. New installations of PHP will choke on the short form PHP tags. Its as simple as that.
But while I'm here... The second problem you have is the horrible mixing in and out of PHP to and from HTML. You should clean up your code so that you don't have to have so many small bits of PHP. Doing it this way makes it virtually impossible to keep track of your tags in HTML and your braces in PHP. Almost guaranteed to lead to errors, and very difficult to read when you come back to it two years down the line to make a bug fix.
To solve this, I would suggest writing your code more like this:
<?php
for($i=1; $i<=$npagine; $i++) {
if($i==$index) {$class='paginas';} else {$class='pagine';}
.... //output your HTML here, without the if() condition embedded in it.
}
?>
You could simplify that even further using a ternary operator.
Switching to the long-form PHP tags <?php actively discourages excessive switching between PHP and HTML in this way, so you may want to take the opportunity to re-write your code in a more readable form.
In a case like this, there's nothing wrong with using print or echo to output the whole of the HTML tag, rather than switching to HTML mode to print it.
So you could end up with code like this:
<?php
for($i=1; $i<=$npagine; $i++) {
$class = ($index == $i) ? 'paginas' : 'pagine';
print "<a class='{$class}' href='index.php?{$splitter_zone}&index={$i}>{$i}</a>";
}
?>
Much simpler and easier to read, I'm sure you'll agree.
One final point I'd make is that I always advise to avoid using single-character variable names like $i. Try to use something more descriptive to what you're using it for. It seems harmless enough, but imagine trying to search a large program for $i to find a bug. You'd get a lot of false hits.
The PHP and HTML is fine (fsvo. "fine"; for one thing, turn off smart-tags!). Dreamweaver doesn't know how to highlight it properly.
for($i=1; $i<=$npagine; $i++) {
$class=$i==$index?"paginas":"pagine";
echo"<a class='{$class}' href='index.php?{$splitter_zone}&index={$i}>{$i}</a>\r\n";
}
I asked another question about HTML and PHP separation as I have seen references to it on tutorial and examples pages but I found that separation of HTML and PHP it something different than what people are actually commenting on and I think that is PHP modes.
That is breaking out of PHP or not. Should It be done? Is it important?
Is it just a matter of preference to echo my HTML output or should I break out to display it?
Example:
<?php
echo '<html'>;
?>
vs.
<?php
dostuff();
?>
<html>
<?
morestuff();
?>
I assume by "breaking out" you mean:
<?php foo(); ?>
test
<?php bar(); ?>
as opposed to
<?php
foo();
echo("test");
bar();
?>
Well, one advantage of the first solution is that your layout is still more or less readable in HTML editors. Also, it separates layout and logic, at least more than the other variant. It is probably also slightly faster than the second option because no strings need to be parsed and echo'ed. On the flipside, having tons and tons of individual PHP-blocks can really be hard to read because things that are semantically related are suddenly split. You can, of course, also combine both approaches.
I think the bottom line here is that as soon as you need to do so much formatting and echo'ing that the logic of your program becomes really obscured, you should consider using a 'real' template engine.
I think it depends on the situation.
how many lines do you want to echo to the browser?
do the lines contain $variable values? $array values?
do you loop trough a dataset? etc etc.
To me, it is more reable to just echo the lines most of the time.
<?php
if ( check($something) ) {
echo "Some variable is: $something<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
can be more readable than:
<?php
if ( check($something) ) {
?>
Some variable is: <?php echo $something; ?><br/>
<?php
} else {
?>
Some variable is something else!<br/>
<?php
}
?>
and with some IDEs (or stackoverflow.com syntaxhighlighting for example), it can even be more readable to use:
<?php
if ( check($something) ) {
echo 'Some variable is: '.$something."<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
In summary:
PHP offers you a lot of options to send content to your client.
The 'best method' differs from case tot case.
Choose the method that is most readable/maintainable and use it consistently.
If by breaking out you mean this sort of thing:
<?php
if($somecondition) {
?>
<!-- Some HTML -->
<?php
}
?>
Then yes, breaking out is better in most cases as it is more readable (many IDES highlight HTML syntax, and cannot do so if it is withing a string when being echo() ed)