Saw a thread about omitting the closing ?>
in PHP scripts and got me wondering.
Take this code:
foo.php
<?php
echo 'This is foo.php';
include('bar.php');
bar.php
<?php
echo 'This is bar.php';
If you create these two scripts and run them, php outputs:
This is foo.php
This is bar.php
(new line added for artistic license before anyone points that out)
So, how come: baz.php
<?php
echo 'This is foo.php';
<?php
echo 'This is bar.php';
results in a predictable syntax error unexpected '<'
, when "include" does just that - or rather, my understanding of include is that PHP just dumps the file at that point as if it had always been there.
Does PHP check for opening tags and ignore future ones if the file is included? Why not do this when there are two sets of tags in one script?
Thanks for any clarification. Not exactly an important issue but would be nice to understand PHP a little more.
The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present. <? php echo "Some text"; ?>
If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file.
There are four different pairs of opening and closing tags which can be used in php. Here is the list of tags. The default syntax starts with "<? php" and ends with "?>".
The include and require statements are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script. include will only produce a warning (E_WARNING) and the script will continue.
If you include a file, PHP internally switches from parsing to literal mode (i.e. what it normally does on a closing tag. That's why this works:
<?php
include 'foo.php';
?>
//foo.php
<?php
echo 'yo';
?>
Even though when inlined it would become
<?php
<?php
echo 'yo';
?>
?>
Because interally it's transformed into something like this (for illustrative purposes, in reality it probably doesn't actually merge the contents of the files, it just jumps between them)
<?php
?>
<?php
echo 'yo';
?>
<?php
?>
You can omit the closing ?> because at the end of the include file, PHP switches back to parsing the including file, regardles of what mode it's currently in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With