php modes breaking out of php or not - php

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)

Related

Are there any restrictions on when you can mix HTML and PHP?

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

What is the logic of several <?php ?> in one file

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.

Using if() {} vs if(): endif; [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between if () { } and if () : endif;
Simple question,
When I started programming PHP I was shown my if statements like this:
If(1 == 1):
Echo 'hello world';
Endif;
Where as most people prefer
If(1== 1) {
Echo 'hello world';
}
Is there any difference? Does is improve the speed of the script or is it Better than the way I do it?
The statement are equals though for a better legibility in a Model View Controller project is better to use
if(1== 1) {
echo 'hello world';
}
in model/controller part and the other one in the View part.
<? if(1 == 1): ?>
<div>..</div>
<? endif;?>
so a web designer/ graphic can better handle html code.
No. However, you should not think about micro optimization (it's the root of all evil), especially since you name yourself a beginner.
The second one is more common, the first one is often more readable when mixing php and html.
There is no speed difference between them. This is an alternate syntax of if.
Some people prefer if() { or some prefer if ():
I personally use if (): when there is a bunch of HTML need to output.
<?php if (condition) : ?>
//some html tags html
<?php endif; ?>
and I use if(condition) { when some php processing to be done.
<?php
if (condition)
{
//other PHP stuff
}
?>
Personally I use alternative syntax when I mix PHP with HTML (its much cleaner this way for me):
<p>
<label>Customer:</label>
<?php echo Form::input('customer', Arr::get($post, 'customer'), array('maxlength' => 80)) ?>
<?php if (isset($errors['customer'])): ?>
<span class="error"><?php echo $errors['customer'] ?></span>
<?php endif ?>
</p>
Other then that there is no difference.
Is there any difference? Does is improve the speed of the script or is it Better than the way I do it?
No.
That's just two different ways to do the same thing.
For the second one almost every good code editor/IDE will highlight the matching brace.
Such a reason, along with the fact that curly braces are compatible with many other languages, makes them used more often.

Print <<< END; question

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 :-)

Opensource project's PHP syntax

When working with open source project (like wordpress, drupal, joomla) I always find in the PHP pages a syntax like (this is an example from drupal):
<?php if ($linked_site_logo or $linked_site_name): ?>
<?php if ($title): ?>
<div class="logo-site-name"><strong>
<?php if ($linked_site_logo): ?><span id="logo"><?php print $linked_site_logo; ?></span><?php endif; ?>
<?php if ($linked_site_name): ?><span id="site-name"><?php print $linked_site_name; ?></span><?php endif; ?>
</strong></div>
<?php else: /* Use h1 when the content title is empty */ ?>
<h1 class="logo-site-name">
<?php if ($linked_site_logo): ?><span id="logo"><?php print $linked_site_logo; ?></span><?php endif; ?>
<?php if ($linked_site_name): ?><span id="site-name"><?php print $linked_site_name; ?></span><?php endif; ?>
</h1>
<?php endif; ?>
<?php endif; ?>
while I do use a different syntax writing my scripts; if I did wrote the previous example it would look something like:
<?php
if($linked_site_logo or $linked_site_name){
if($title){
echo '<div class="logo-site-name"><strong>';
if($linked_site_logo){ echo '<span id="logo">' . $linked_site_logo . '</span>'; }
if($linked_site_name){ echo '<span id="site-name">' . $linked_site_name . '</span>'; }
echo '</strong></div>';
}else{ /* Use h1 when the content title is empty */
echo '<h1 class="logo-site-name">';
if($linked_site_logo){ echo '<span id="logo">' . $linked_site_logo . '</span>'; }
if($linked_site_name){ echo '<span id="site-name">' . $linked_site_name . '</span>'; }
echo '</h1>';
}
}
?>
Now, lets skip the 'appareance' of the 2 syntax methods, becose it is maybe a matter of taste and/or custom (obviously I prefer the second method), the question is:
Does the first syntax (breakinf the 'if' statements, output the HTML instead of echo it, have a lot of PHP snippets even if they arent really needed) have some technical advantages over the second one? (for example the script run faster, is easier to debug, etc...)
Or is just a open source programmers unwrited convention?
It's all about readability.
I don't know what you mean by output vs echo. There is no difference. They're just different ways of printing "stuff" to output that is sent to the client.
The disadvantage of:
echo "<div id=\"blah\">";
is twofold:
The extra slashes require effort to put in and make it less readable; and
HTML outside PHP code blocks will syntax highlighted by most PHP editors.
I wouldn't go as far as saying echoing HTML is evil in all cases, but it certainly has a lot of drawbacks. In addition to what cletus points out, your HTML is not structured anymore, i.e. the indention levels give you no indication of where you are in the document structure. That's a biggie for me.
Personally, I dislike the first style as well, as it makes the PHP code harder to read. I always try to strike a balance, multi-line PHP statements belong in one <?php ?> block, but HTML always belongs outside the <?php ?> block. In edge cases, e.g. when indention levels change inside the PHP block, I tend towards closing it and beginning a new block.
I can see that that opens up a can of worms regarding edge cases and when to use which, so I'm sympathetic to open source projects setting a formal rule to always close <?php ?> blocks.
The biggest "advantage" I could see to the former method would be that it's easier to insert HTML anywhere within the overall control flow - if you wanted to output some HTML before the if($title) check, you could just insert a line above it with the HTML, no need to escape things for an echo or whatnot.
afaik The reason for this is that graphic designers can edit the HTML in their tools (dreamweaver and similar). Those tools would show the php tags as just that or even hide them completely. That way they can design away without touching your code, which is, believe me, a massive advantage when collaborating with designers.
Actually they are not the same. in fact in your second example, php interpreter will do unnecessary step, which is printing out html elements. thus resulting poor performance depending on the size of the page. checout google's article "lets make web faster" http://code.google.com/speed/articles/optimizing-php.html.
They are the same. I suggest you stick what you have been used to do because that is more readable to you.
If you follow MVC - you have the view and model (domain logic) parts. For the view you use the first method because it's HTML with tiny PHP parts in it, and for the model you use the second method - it's pure PHP anyway. It's a very common approach afaik.
Examples:
Zend Framework - see zend view manual
WordPress - the code (even messy parts) are method 2, and the themes are method 1
Keeping one hierarchy of consistent indentation for both code and markup is essential for coping with complex templates. In the first example I can immediately see the structure of the tags; the second makes me work to understand what's going on. Without reading through it I can't see whether it's doing something like leaving an element open. IMO PHP should be written like XHTML, as if the ‘if’ statements were tags you had to balance.
(Personally though I prefer the standard {...} syntax to the alternative :...endif one. I don't see what advantage that brings.)
Legend has it that direct PHP-templated output is marginally faster than echoing everything. But if there's really any difference it's too small for me to measure. Certainly compared to any other work your script will be doing, it's inconsequential. t's only the readability that really matters. PHP is a templating language, though — you might as well take advantage of it!
[both examples fail to htmlspecialchars, tsk.]

Categories