Consider this:
#!/usr/bin/php
<?php
class Foo {
static function bar () {
echo "Foo->bar
";
}
}
if (PHP_SAPI === 'cli') {
Foo::bar();
}
?>
I can execute this from CLI, but when I include
it in, say, a CGI-run PHP script, the shebang ends up in the output.
I like simple scripts compact: I guess I could put the class
part in a separate "lib"-file and have a simple wrapper for CLI use. BUT I'd like to keep it all in one place without having to worry about include paths etc.
Is this possible without ob_*
-wrapping the include
to capture the shebang (if this is even possible), or is it dumb to cram all of this into one file anyway? Alternatives/Thoughts/Best Practices welcome!
Edit: I'd like to put the script in my PATH
, so calling I'd rather not call it by php file.php
. See my comment to @misplacedme's answer
It's actually easy.
Remove the shebang and when you run the script, run it asphp scriptname.php
OR /path/to/php scriptname.php
instead of./scriptname.php
Running php script.php
will look in only the current directory, or any directory within PATH. If you absolutely have to run it that way, add it. export PATH=$PATH:/path/to/php/script/folder
(in bash)
That will mess up includes unless you're using full paths within the script.
No matter what you do, you'll have to use full paths somewhere.