Skip to content

Instantly share code, notes, and snippets.

@CHH
Created May 18, 2012 10:13
Show Gist options
  • Save CHH/2724449 to your computer and use it in GitHub Desktop.
Save CHH/2724449 to your computer and use it in GitHub Desktop.
Run something only when the file is invoked on the command line.
<?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();
}
<?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();
}
% 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