note 14532 deleted from language.basic-syntax.instruction-separation by jimw

From: Date: Wed, 31 Oct 2001 01:44:51 +0000
Subject: note 14532 deleted from language.basic-syntax.instruction-separation by jimw
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-19677@lists.php.net to get a copy of this message
JavaScript writers, be careful: PHP does not support implicit end of instructions on line breaks, the trailing semicolon is required, except before ?> where it is implied. Note that because ?> implicitly generates an end of instruction (in fact it generates something like "; echo<<<"<?"), the following code does not work as expected: <?php ... if(condition) ?>FOO<?php else ?>BAR<?php ... ?> because it is syntaxically equivalent to: <?php ... if(condition); echo "FOO"; else; echo "BAR"; ... ?> and this produces a parse error... Each <? and ?> imply an end of instruction: the sequence "?>" terminates the previous PHP instruction as if there as a semi-colon, and this terminates the above if() instruction, before an implicit echo() gets generated. The sequence "<?" or "<?php" implicitly terminates the implied echo() instruction which above generates the "FOO" output. It implicitly generates a semicolon. So the above if() is followed by two statements (an empty statement which terminates, and the implied echo statement which terminates the if). The parse error comes from a simple "else" clause after two statements, the last one not being an if statement. The correct way to generate conditionnal or looping code is by using braces (because empty statements are valid in PHP): <?php ... if(condition){ ?>FOO<?php }else{ ?>BAR<?php } ... ?> which is equivalent to: <?php ... if(condition){ ; echo "FOO"; }else{ ; echo "BAR"; } ... ?> Also note that PHP starts reading a script by assuming an implied echo stantement at the beginning of the file before it detects the first "<?" or "<?php" sequence which terminates this echo... A PHP script which does not start by a "<?" or "<?php" sequence is then a valid script. One can directly reference PHP $variables at the top of the file if they are predefined (for example from a main script that includes that script)... A PHP script that starts with "<?" or "<?php" is implictly creating an echo statement but with empty contents, so PHP silently suppresses this null echo statement, allowing a script to generate headers after it... If your PHP script starts with a blank line before the leading "<?" or "<?php" sequence, this blank line will get generated on the output, forbidding any further HTTP Headers() or cookies in the first scripted fragment...

« previous php.notes (#19677) next »