Php include and end tag

Saw a thread about closing exception ?> In PHP scripts and made me wonder.

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 art license before anyone points this out)

So, how did it turn out: baz.php

 <?php echo 'This is foo.php'; <?php echo 'This is bar.php'; 

leads to a predictable syntax error of unexpected '<' when "include" does just that - or rather, my understanding of inclusion is that PHP just uploads the file at that moment, as if it were always there.

Does PHP check for opening tags and ignoring future tags if the file is included? Why not do it when there are two sets of tags in one script?

Thanks for any clarification. Not really an important issue, but it would be nice to understand PHP a little more.

+7
include php tags
source share
4 answers

If you include the file, PHP internally switches from parsing to literal mode (i.e. what it usually does on the closing tag, so this works:

 <?php include 'foo.php'; ?> //foo.php <?php echo 'yo'; ?> 

Despite the fact that upon insertion it will become

 <?php <?php echo 'yo'; ?> ?> 

Because it has turned into something like this (for illustrative purposes, in fact, it probably does not actually merge the contents of the files, it just jumps between them)

 <?php ?> <?php echo 'yo'; ?> <?php ?> 

Can you omit the closing? >, because at the end of the included file, PHP switches to parsing the included file, taking into account the mode in which it is located.

+9
source share

Personal Assumption:

When you write include('bar.php'); , the parser reads the contents of fo bar.php and inserts it into foo.php , when reading it, it probably deletes the start <?php , since it recognizes the entire contents of bar.php - this is PHP code, therefore, the result does not lead to an error.

+2
source share

This may help to think about it, since PHP does not include another page inside the first, since PHP does not create an internal file with all the pages included inside, and then analyzes it.

What he does is that he parses the first file, finds the include , and then stops parsing the first file and starts parsing the included file. When a file is included, it resumes parsing the original file where it was stopped. (This is quite a bit simplified.)

+1
source share

I read somewhere about the exception of both opening and closing php tags.

The problem when I do this is that my editor does not format the files as php files, but like regular text files.

so far i have not had any problems with any included tag file. I do not know if the behavior used for impairment uses tags or not.

0
source share

All Articles