why is there different syntax same outcome? - php

Why is there different syntax same outcome?
For example
# Example 1
if($myCondition == true) :
#my code here
endif;
if($myCondition == true) {
#my code here
}
# Example 2
foreach($films as $film) :
#my code here
endforeach;
foreach($films as $film) {
#my code here
}
Also I have been using <?= for ages now and I now understand that is deprecated and I should be using <?php echo Is this the case and why? It's a lot more annoying to have to write that out each time.
What are your thoughts?

The colon endif, endforeach, etc syntax is known as Alternative Syntax. I can't say for certain why this functionality exists, just that it does and is supported. I can say that I've noticed the alternative syntax used more for templating purposes where it's easy to pick out an endif/endforeach than it is a closing curly-brace in the middle of HTML markup.
The <?= is known as the short open tag. You can probably find all the info you need about its use here Are PHP short tags acceptable to use?

Why should the outcome be different? The one without the brackets is called alternative syntax for control structures and is very useful, e.g. when dealing with HTML.
<?php echo is much more portable because short open tags can be disabled and are disabled by default since PHP 5.3

Related

Difference between php inside html and vice versa

I was always curious, is there any significant advantage or disadvantage of writing php inside html or vice versa
example:
echo '<ul>'
foreach ($items as $item)
{
echo "<li>$item</li>";
}
echo '</ul>
As opposed to:
<ul>
<? foreach($items as $item): ?>
<li>$item</li>
<? endforeach; ?>
</ul>
Since these essentially generate the same thing, when would you actually use one over the other?
Functionally they are the exact same and won't have an appreciable affect on performance, if any. It comes down to personal preference and readability - if one is clearer than the other and will be easier for others (or the future you) to understand, go with that one.
I personally find it better to use the latter if you actually have PHP in a mostly HTML file. The clear opening/closing tags match up visually with HTML easier. I find it can be hard to line up curly braces visually.
As an example, in the case of a MVC framework I would use the first way of outputting things in a controller or model context, while the second way in my view files. Some templating languages like smarty have similar looking constructs.
ie:
{ if [condition] }
{ /if }
The first one echoes meaningless strings from the IDE's point of view, whereas the latter one is a mix of HTML and PHP and will be handled properly by your editor. In other words, it's better to actually separate HTML from PHP as it allows your editor to parse HTML and provide some usefull features like syntax validation or autoclosing of HTML tags.
basically php is a server side scripting and html is client side scripting. So if it is php inside html then it generates faster response and you can format a better view. However for some scenario you might have to consider the other case for developing.

php syntax with ":", use it or not?

I like to use the syntax with ":" and the "end-stuff".
if($var=='patate'):
echo 'excellent';
else :
...
endif;
I know IDE are used to the {} syntax when it's time to collapse code, but other than that, is there any reason to NOT use this ":" syntax ?
Don't use it. It's ugly and people usually expect the curly-braces syntax they are used to. It's most common when mixing PHP and HTML in the same file (i.e. when using PHP as a template engine) - but you shouldn't do that anyway, at least not if the same file also contains your application logic.
Autoindent scripts will also have trouble indenting your code properly since they usually just know one curly brace = one more/less level of indentation.
However, if you do like : instead of { have a look at python. :)
The alternate syntax is of occasional use if you're in the habit of mixing PHP and HTML blocks, e.g.
<?php if ($something): ?>
<h2>blah blah blah</h2>
<?php endif; ?>
But if you're using a decent syntax-highlighting editor, there's pretty much no point in using it, as the colorization will give you all the contextual hints you need as to what's PHP and what's HTML. And editors like VIM which let you "bounce" on brackets/braces also negate the need - you can't bounce on an 'endif'.
The main reason that people are against using the alternate syntax is because some server configurations may not allow it. If you don't control your server environment or need to share code with others, then it may be best to shy away from using the alternate syntax.

PHP' if' spanning in different code blocks

Ok, someone has just shown me a piece of PHP code and at the end of the file I've seen a stray <?php } ?> . I thought that should give a compilation error, but it doesn't.
Why is:
<?php
if(1==1){
?>
X
<?php } ?>
valid?
Is it safe to split a statement into multiple php blocks?
PS: I was expecting for something more from the answers then "yes" :D
Yes that is fine, but I would suggest:
<?php if(1==1):?>
X
<?php endif; ?>
It makes it a little more readable then random { and }
From the manual:
Everything outside of a pair of opening and closing tags is ignored by
the PHP parser which allows PHP files to have mixed content. This
allows PHP to be embedded in HTML documents, for example to create
templates.
Welcome to the mysterious world of PHP.
Safe? Yes.
Readable? Not really.
Avoid mixing your PHP logic with your HTML where possible. There are few times when this is a good idea, as it makes reading through and understanding your code difficult.
Yes, this is fine.
It's often useful to drop out of "php mode" for large blocks of HTML - you'll see this technique used anywhere HTML and PHP are mixed.
It is valid, but not recommended if you want to have a code that is maintainable and readable in the long run.
You must bear in mind that every time you "exit" from PHP, you are entering HTML.

How to use { in place of opening tags and } in place of closing tags?

I am an MVC addict.
I have some views in plain PHP (not using any Templating Engine (TE) such as Smarty for getting good performance), but without Smarty my views are looking ugly and hard to code.
I'm wondering how can I make them look good (ie., human readable) without using any TE? At least I want to replace those <?php and ?> for sure, or if you have any other better idea?
It's just a start of my web application so please guide me to any better alternative if you have any.
Thanks.
In templates I use the alternatives of PHP like:
<?php if (true): ?>
<?php endif ?>
<?php foreach ($x as $y): ?>
<?php endforeach ?>
etc.
http://php.net/manual/en/control-structures.alternative-syntax.php
There's no PHP variation or syntax that allows you to replace <?php and ?> with { and }. If you want that, you'll need to use or write a custom parser for it, which means you're looking at a templating engine. No templating engine, no custom syntax.

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