ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: main - python-like if __name__ == __main__
Submitter: Mirek Rusin (other recipes)
Last Updated: 2004/09/09
Version no: 1.0
Category:

 

5 stars 1 vote(s)


Description:

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

Source: Text Source

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

Discussion:



Add comment

Number of comments: 1

debug backtrace works for files served by Apache as well, Simeon Franklin, 2006/10/09
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');
}
?>

Add comment



Highest rated recipes:

1. DB_eSession PHP class ...

2. main - python-like if ...

3. iPHP: Semi-interactive ...

4. tinySendMail

5. Microsoft Access ...

6. Single Linked List

7. PHP MySQL Search Class

8. Pass Javascript arrays ...

9. Microsoft Access ...

10. Password generation




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.