When you use include
PHP is internally reading the file and including it where your include directive is. It's akin to copying and pasting the file contents into the location where the include
directive is, but without being inside a PHP code block.
For example:
file1.php
#!/usr/bin/env php
<?php
//file 1 code
?>
file2.php
<?php
// some code
include 'file1.php';
// some more code
?>
Results in the following:
<?php
//some code
?>
#!/usr/bin/env php
<?php
//file 1 code
?>
<?php
// some more code
?>
Because the #!
is outside of the PHP start/end tags (<?) it's treated as raw text to output and PHP is not looking to see if there are comments there. This is correct and expected behaviour.
As for the the shebang line itself (sorry if this seems condescending, it's just to be absolutely clear to other readers), is parsed and processed by the kernel when you execute a file, not PHP. When you attempt to execute a script, the kernel checks the first line of the script (the shebang line) to see if it starts with "#!". If it does, the kernel knows that the script requires an interpreter to execute it.
The kernel extracts the path specified in the shebang line, which points to the desired interpreter. In the example above, it would extract /usr/bin/env php
.
The kernel then executes the specified interpreter and passes the path of the script as an argument to the interpreter. The interpreter (in this case, PHP) takes over and processes the script according to its syntax and semantics.
As the PHP cli executable knows and supports the shebang syntax, it skips this one line when processing this one file at startup, it will not look for this again. As such, your included file will output any content either from a PHP echo
or content that is not contained with the PHP code block tags.
You can prove this to yourself by creating the following file and executing it
#!/usr/bin/env php
#This will output to STDOUT, it's not a comment because it's outside of the PHP code blocks
<?PHP
# This is a comment
?>
Which results in:
geoff@pc:~$ ./test.php
#This will output to STDOUT, it's not a comment because it's outside of the PHP code blocks
The fact that you are having this issue isn't due to PHP but rather a design fault of your application, a script to execute on the command line should never be used as a file to include
(as you have discovered). If you need two separate entry points for your code, you need to put your common code in a common file, for example:
common.php
function someFunction()
{
//DoStuff
}
command.php
#!/usr/bin/env php
<?PHP
include 'common.php';
someFunction();
?>
index.php
<?PHP
include 'common.php';
someFunction();
?>