Sandman Sandman - 6 months ago 27
PHP Question

Python like standalone vs. library use checking for PHP

I know Python has name="__main__" check to test if the script is called as a standalone unit of execution or is included in another file to use as a library. Does PHP have a similar test? One way to do this would be:

define('ASLIBRARY', true);

And in foobar.php

$aslibrary = defined('ASLIBRARY');
if (!aslibrary) {

If PHP provides something of the sort, this would obviously be redundant.


Something like this should work:


$_SERVER['SCRIPT_FILENAME'] refers to the script that is currently executing - if we're in an included file, this still references the initial script, the one doing the including.

__FILE__, on the other hand, is a magic constant which will always be the current file, whether included or run directly.

If they're the same, then we're in the directly-called script.

Otherwise... well, you get the idea :)