Jump to content

Open and close and open again PHP tags


Zane

Recommended Posts

Not to say that this occurs in every php software out there, but I far too occasionally notice that the application is written with scattered php open and close tags, for instance

<?php if(true) ?>
<?php { ?>
Blah blah blah, because it's true
<?php } else { ?>
because it's not true
<?php } ?>

To me, it is extremely irritating.

 

Regardless, I see a lot of open source software written this way and I can't help but think that there must be some underlying reason for it.  Magento, for example, is written exactly in this manner.  The templates are infested with these opened and closed php snippets.  Obscurity is not security so I'm ruling security reasons out.  Maybe it is more efficient? -- But I couldn't understand why, if so.  It seems like that would put more of a drag on the system itself causing php to start and stop parsing continually and excessively, then again, I'm no expert in the field of memory consumption and other operating system complexities.

 

Honestly, in my opinion, it is stupid.  i would never write a program that way..   HEREDOCs are much more useful and eye pleasing than that awful <?php { ?>

 

I had the misfortune a few months ago when I purchased an invoicing/customer maintenance system that I didn't know was written for PHP 5.2 or something lower, one that allowed short tags; and thus short tags were used in the same manner as I've described.

 

Is this just plain disorganization or is there some deep-seated inner lining advantage that I'm not aware of?

Link to comment
Share on other sites

Personally I use the alternative syntax in my views:

<?php if (some_condition): ?>
<h2>Yay, it passed</h2>
<?php else: ?>
<h3>It didn't pass</h3>
<?php endif; ?>

Then my editor still respects the HTML syntax highlighting since it's still separate, the php highlighting, as well as not using the stupid braces, which I also abhor.

Link to comment
Share on other sites

I hate using heredoc for output. There's no IDE support for HTML inside strings, to name one problem with it. So I do exactly that kind of open/close stuff - especially if I have to jump between logic and HTML a lot.

 

Rules I follow:

1. A line with PHP code is wrapped in open and close tags. The entire line.

2. If I want a block of code, open tag + blank line + code + blank line + (if not at the end of the file) close tag

3. Open tag is always at the beginning of the line. Indentation happens right after.

<?php foreach ($objects as $object) { ?>
<div class="object">
	<h2><?=$object->name?></h2>
<?php	if ($object->hasProperties()) { ?>
	<h3>Properties</h3>
	<table class="object-properties">
<?php		foreach ($object->getProperties() as $name => $value) { ?>
<?php

			switch (true) {
				case is_scalar($value):
					$printable = "(" . gettype($value) . ") " . $value;
					break;
				case is_array($value):
					$printable = "array(" . count($value) . ")";
					break;	
				case is_object($value):
					$printable = "object(" . get_class($value) . ")";
					break;
				default:
					$printable = gettype($value) . ": " . @(string)$value;
					break;
			}

?>
		<tr>
			<th><?=$name?></th>
			<td><?=$printable?></td>
		</tr>
<?php		} ?>
	</table>
<?php	} ?>
</div>
<?php } ?>
I also tend to have my IDE set up to color HTML differently from PHP code so there's that visual distinction, not to mention the obvious presence of a "<?php" at the beginning of the line.
Link to comment
Share on other sites

I'll try to do as much as can for processing and minimal in the html.

 

In templates is usually more html and dabble the php where it needs it, but never breaking in and out just braces

 

Sometimes I'd rather just echo out the html.

<?php
foreach ($objects as $object) {
    
    echo "<div class='object'>";
    echo "<h2>{$object->name}</h2>";
    
    if ($object->hasProperties()) {
        
        echo "<h3>Properties</h3>";
        echo "<table class='object-properties'>";
        
        foreach ($object->getProperties() as $name => $value) {
            
            switch (true) {
                case is_scalar($value):
                    $printable = "(" . gettype($value) . ") " . $value;
                    break;
                case is_array($value):
                    $printable = "array(" . count($value) . ")";
                    break;
                case is_object($value):
                    $printable = "object(" . get_class($value) . ")";
                    break;
                default:
                    $printable = gettype($value) . ": " . @(string) $value;
                    break;
            }
            
            echo "<tr>";
            echo "<th>$name</th>";
            echo "<td>$printable</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    echo "</div>";
}
?>
Edited by QuickOldCar
Link to comment
Share on other sites

...I far too occasionally notice that the application is written with scattered php open and close tags...

 

At least I'm not the only person who gets irritated by this type of coding. For me, all those open and close PHP tags add too much noise. The simplicity of having most of my code in PHP outweighs the advantage of code coloring. With that said, I will break out of PHP for large blocks of HTML code.

Link to comment
Share on other sites

I always thought it was a Dreamweaver (which I don't use) thing that cause every single line of PHP code to have open/close tags. My preference is to first try and separate logic from presentation as much as possible. So, files tend to be mostly PHP or mostly HTML. In PHP heavy files, I will just typically put HTML code within quoted strings since the code highlighting doesn't provide a lot of value. Where I need PHP code in presentation files, I will use something similar to requinix's example above.

Link to comment
Share on other sites

So it all boils down to preference and convenience then.  Nothing extra-efficient in using it.

 

Here, though, is an example of a usage of those semantics in a very aggravating way.

<?php
/**
 * Product list template
 *
 * @see Mage_Catalog_Block_Product_List
 */
?>
<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<div class="category-products">
    <?php echo $this->getToolbarHtml() ?>
    <?php // List mode ?>
    <?php if($this->getMode()!='grid'): ?>
    <?php $_iterator = 0; ?>
    <ol class="products-list" id="products-list">

This is just a small snippet from Magento's files.

Link to comment
Share on other sites

I wouldn't read too much into those templates. A lot of Magento people are unhappy with it as well, so it's probably just legacy garbage. They considered moving to Twig, but decided that it was too much effort to rewrite all old templates.

 

Generally speaking, this template style mostly boils down to igorance and stupidity.

 

There are lots of excellent template engines (like Twig) which offer readable syntax, high performance and increased security all at the same time. Yet still many programmers refuse to use them and stick to plain PHP. Well, OK, there's an alternative PHP syntax specifcally for templates. But again a lot of PHP programmers just don't use it and instead clutter their code with loose braces all over the place. Why? Because they've always done it like that.

 

I've discussed this topic many, many times, but you just hit a wall. I think we'll have to live with the fact that many PHP people want awful code. They produce the legacy shit today that we have to fix tomorrow.

<?php echo 'T' ?>
<?php echo 'h' ?>
<?php echo 'a' ?>
<?php echo 'n' ?>
<?php echo 'k' ?>
<?php echo ' ' ?>
<?php echo 'y' ?>
<?php echo 'o' ?>
<?php echo 'u' ?>
<?php echo ',' ?>
<?php echo ' ' ?>
<?php echo 'P' ?>
<?php echo 'H' ?>
<?php echo 'P' ?>
Link to comment
Share on other sites

 

<?php echo 'T' ?>
<?php echo 'h' ?>
<?php echo 'a' ?>
<?php echo 'n' ?>
<?php echo 'k' ?>
<?php echo ' ' ?>
<?php echo 'y' ?>
<?php echo 'o' ?>
<?php echo 'u' ?>
<?php echo ',' ?>
<?php echo ' ' ?>
<?php echo 'P' ?>
<?php echo 'H' ?>
<?php echo 'P' ?>

 

That is horrible. Short echo tags to the rescue!

<?='T'?><?='h'?><?='a'?><?='n'?><?='k'?><?=' '?><?='y'?><?='o'?><?='u'?><?=','?><?=' '?><?='P'?><?='H'?><?='P'?>
  • Like 4
Link to comment
Share on other sites

  • 3 weeks later...

I have always prefer this method of outputting HTML in blocks of echo [or print_r() ] personally, my reasoning is "mostly" everyone should know what HTML is and not much need for it to be highlighted in syntax. But it dose boil down to personal preference.

 

if(!isset($_POST["submit"])){// if there was no submit variable passed to the script (i.e. user has visited the page without clicking submit), display the form:
    if(!empty($_SESSION["MSG"])){echo '<div class="MSG">' . $_SESSION["MSG"] . '</div><br /><br />';}
    echo '<form name="LoginForm" class="formbox" id="LoginForm" action="index.php" method="post" />
    Username: <input type="text" name="username" id="username"/><br />
    Password: <input type="password" name="password"><br />
    <input type="submit" name="submit" id="submit" value="submit" />
    </form>';
    unset($_SESSION["MSG"]);
}elseif(isset($_POST["submit"]){//do stuff
}

Link to comment
Share on other sites

if(!isset($_POST["submit"])){// if there was no submit variable passed to the script (i.e. user has visited the page without clicking submit), display the form:

 

So, if the user submits a form by pressing the Enter key on their keyboard you just ignore the submission? Kind of an odd way to treat your users, but to each his own.

Link to comment
Share on other sites

So, if the user submits a form by pressing the Enter key on their keyboard you just ignore the submission? Kind of an odd way to treat your users, but to each his own.

Hitting Enter is equivalent to clicking the form's default submit button (which subjects it to disabled buttons, click events, etc).

http://www.w3.org/TR/html5/forms.html#implicit-submission

Link to comment
Share on other sites

So, if the user submits a form by pressing the Enter key on their keyboard you just ignore the submission? Kind of an odd way to treat your users, but to each his own.

I was trying to keep my post short and on topic that is all. But ill post a revision here just for you.

if(!isset($_POST["submit"])){// if there was no submit variable passed to the script (i.e. user has visited the page without clicking submit), display the form:
    if(!empty($_SESSION["MSG"])){echo '<div class="MSG">' . $_SESSION["MSG"] . '</div><br /><br />';}
    echo '<form name="LoginForm" class="formbox" id="LoginForm" action="index.php" method="post" />
    Username: <input type="text" name="username" id="username"/><br />
    Password: <input type="password" name="password"><br />
    <input type="submit" name="submit" id="submit" value="submit" />
    </form>';
    unset($_SESSION["MSG"]);

}elseif(!empty($_POST["username"]) && !empty($_POST["password"])){//do stuff

}else{// Else the user hit submit without all required fields being filled out:
$_SESSION['MSG'] = '</br>Please Complete all fields</br>';
exit(header('Location: ./index.php', false));
}
Link to comment
Share on other sites

Hitting Enter is equivalent to clicking the form's default submit button (which subjects it to disabled buttons, click events, etc).

http://www.w3.org/TR/html5/forms.html#implicit-submission

 That is true, yes. But unfortunately not all browsers will pass the value of an INPUT TYPE="SUBMIT" when the form is posted using the enter key (may not be the case with current browsers, haven't checked in a while). Checking the REQUEST_METHOD is a sure fire way to know if a form was POSTed.

  • Like 1
Link to comment
Share on other sites

 That is true, yes. But unfortunately not all browsers will pass the value of an INPUT TYPE="SUBMIT" when the form is posted using the enter key (may not be the case with current browsers, haven't checked in a while). Checking the REQUEST_METHOD is a sure fire way to know if a form was POSTed.

 

+1. I think the enter problem only exists in IE 10 and below, but still it is better to be on the safe side. Also I think older browsers would have the same problem too.

 

To stay on topic, I am with the author - I too, use the HEREDOC syntax, I love it. Breaking out of PHP constantly is annoying and I am not sure exactly how faster your program will be. Also, the HEREDOC forces you to store the values of all functions inside variables which in return would make your program faster, since you couldn't be lazy that way. 

 

Well technically you could put a function in the HEREDOC but it is quite complex.  

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.