Welcome, guest | Sign In | My Account | Store | Cart

How to determine if we're in the (directly) launched script.

PHP, 25 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
There is a way to tell if we're actually in the script
which was directly launched.

Just like in Python there is:

if __name__ == '__main__':
    pass

...in PHP it looks like this:

if (basename($argv[0]) == basename(__FILE__)) {
    main();
}

I'm using this trick with PHPUnit testing:

// Test
if (basename($argv[0]) == basename(__FILE__)) {
    include substr(__FILE__, 0, -4) . 'Test.php';
}

Very, very useful.

Have a fun,
Mirek Rusin, Poland, Rzeszow

1 comment

Simeon Franklin 17 years, 5 months ago  # | flag

debug backtrace works for files served by Apache as well. Checking the basename only works under the CLI version of PHP. Harry Fuecks solicited comments on this issue once and the best solution was to check the results of debug_backtrace(). If this returns an empty array than you aren't in an included file...

I use this feature to include unit tests in library style files that are normally used by include but have some sanity checks in the "if directly executed" section.

You can test the two methods (and see that debug_backtrace works from both CLI and SAPI interfaces) by running the following code:

<?php
if (basename($argv[0]) == basename(__FILE__)) {
    print('basename check works');
}
if(count(debug_backtrace()) == 0)
{
    print('debug_backtrace works');
}
?>
Created by Mirek Rusin on Thu, 9 Sep 2004 (MIT)
PHP recipes (51)
Mirek Rusin's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks