Skip to content

Instantly share code, notes, and snippets.

@pconerly
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pconerly/9083065 to your computer and use it in GitHub Desktop.
Save pconerly/9083065 to your computer and use it in GitHub Desktop.
python's `if __name__ == "__main__"`, but for php.
A slightly fuller example for this stackoverflow question: PHP equivalent of Python's name == “main”?

If you run php import.php the expected output is:

$ php import.php 
I am import.php
I am import.php, and I was run from the command line.

If you run php run.php the expected output is:

$ php run.php 
I am run.php
I am import.php
I am run.php, and I was run from the command line.
<?php
print_r("I am import.php\n");
// If this is the file that was run from the command line.
if (!debug_backtrace()) {
// do useful stuff
print_r("I am import.php, and I was run from the command line.\n");
}
<?php
print_r("I am run.php\n");
require_once('import.php');
if (!debug_backtrace()) {
// do useful stuff
print_r("I am run.php, and I was run from the command line.\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment