Created
May 18, 2012 10:13
-
-
Save CHH/2724449 to your computer and use it in GitHub Desktop.
Run something only when the file is invoked on the command line.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# Some regular library code, which can be used by including | |
# the file. | |
class Foo | |
{ | |
# Do not use a global function, because you get an error | |
# if you try to redefine it. | |
static function __main() | |
{ | |
echo "Hey there on the command line!\n"; | |
} | |
} | |
# We must use realpath(), because the first argument | |
# only contains the relative path and __FILE__ contains | |
# the absolute path to this file. | |
if (__FILE__ === realpath($_SERVER['argv'][0])) { | |
Foo::__main(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# Alternative version, using an anonymous function. | |
# Some regular library code, which can be used by including | |
# the file. | |
class Foo | |
{ | |
} | |
# Do not use a global function, because you get an error | |
# if you try to redefine it. | |
$__main = function() { | |
echo "Hey there on the command line!\n"; | |
}; | |
# We must use realpath(), because the first argument | |
# only contains the relative path and __FILE__ contains | |
# the absolute path to this file. | |
if (__FILE__ === realpath($_SERVER['argv'][0])) { | |
$__main(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% php cli.php | |
Hey there on the command line! | |
% php -a | |
% include("cli.php"); | |
% var_export(class_exists("Foo")); | |
true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment