Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php include and closing tag

Tags:

include

php

tags

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.

like image 673
Ross Avatar asked Nov 23 '10 09:11

Ross


People also ask

What is the closing tag for PHP?

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"; ?>

Is it necessary to close PHP tag?

If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file.

What is the opening and closing tag of a PHP program?

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 "?>".

What is the difference between include and require in PHP?

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.


1 Answers

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.

like image 115
Bart van Heukelom Avatar answered Sep 21 '22 07:09

Bart van Heukelom