Python __name__ == __main__ in PHP

Share this article

One of those nice features of Python, that marks it as a language designed for developers (as opposed to one designed for tool vendors) is the ability to conditionally run some logic if you’re executing a script directly but ignore it if the script is being imported (“included”) by another script.

For example;

class User: def setName(self, name): self.name = name def getName(self): return self.name # Only execute this we're "main"... if __name__ == "__main__": u = User() u.setName("Harry") print u.getName()

The code after the ‘if __name__ == “__main__”:’ is only executed is I run this script directly. If I import the User class from another script it is ignored.

Makes a very handy tool for testing (or better yet unit testing) a Python script. So much so I want it in PHP.

One trick to do so is like this;

< ?php class User { var $name; function setName($name) { $this->name = $name; } function getName() { return $this->name; } } if ( realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME']) ) { $u = & new User(); $u->setName("Harry"); print $u->getName(); } ?>

This relies on the predefined constant __FILE__ which gets populated with the name of script where __FILE__ is accessed (i.e. it works irrespective of includes). The value of __FILE__ should be unique to the script, as far as I know.

There’s two problems here though. First if you use this approach alot, there’s going to tons of calls to realpath(), meaning a performance hit. Also $_SERVER[‘SCRIPT_FILENAME’] returns the name of the PHP executable when using PHP via CGI and otherwise probably can’t be relied upon on web servers other than Apache.

Another approach would be to conditionally define a constant using the value of __FILE__ e.g.;

class User { // .... } if ( !defined('__MAIN__') ) { define ('__MAIN__',__FILE__); } if ( __FILE__ == __MAIN__ ) { $u = & new User(); $u->setName("Harry"); print $u->getName(); }

If the constant __MAIN__ hasn’t already been defined (by a script which included this one), it gets assigned the value of __FILE__ and the conditional code block is executed.

This approach is probably most trustworthy in that it should work on any PHP install but requires additional work and if you forget to define __MAIN__ somewhere you may end up with code being executed that you weren’t expecting.

Note that the following;

@define ('__MAIN__',__FILE__);

The @ operator, used to suppress the error notice if __MAIN__ was already defined, is slower than using is_defined().

The third option, which I’m not sure I 100% trust to work correctly everywhere, is to use get_included_files() like;

class User { // ... } if ( __FILE__ == array_shift(get_included_files()) ) { $u = & new User(); $u->setName("Harry"); print $u->getName(); }

This is based on the assumptions that the file where execution began will always be the first element in the list returned by get_included_files() (which, as far as I know, it should be) and that it will match the value of __FILE__. So long as this script wasn’t included (or required) by any other, the code inside the if condition is executed.

Of course the overall approach comes cost of parsing the code inside the condition, which can only be avoided using a OPCODE cache like the Zend Accelerator but it makes a useful tool when you’re building modular code and want to develop and test “modules” in your app without running the entire application.

Frequently Asked Questions (FAQs) about Python’s __name__ == “__main__” in PHP

What is the equivalent of Python’s

name == “main” in PHP?

In Python, the name == “main” is used to check whether the script is being run directly or it’s being imported. In PHP, there isn’t a direct equivalent of this. However, you can achieve similar functionality by checking if the file was included or directly accessed. This can be done using the debug_backtrace() function. If the file was directly accessed, the debug_backtrace() function will return an empty array.

How does the

name == “main” function work in Python?

In Python, every module has a built-in attribute called name. When the script is run by itself, the name attribute is set to “main“. However, when the script is imported as a module in another script, the name attribute is set to the name of the script/module. The name == “main” function checks whether the script is being run directly or it’s being imported.

Why is there no

name == “main” equivalent in PHP?

PHP is a server-side scripting language primarily designed for web development. Unlike Python, which is a general-purpose programming language, PHP scripts are usually embedded within HTML and are often designed to be run in response to a web request. Therefore, the concept of a script being “run directly” or “imported” doesn’t apply in the same way as it does in Python.

How can I achieve similar functionality to

name == “main” in PHP?

You can use the debug_backtrace() function in PHP to check if a file was included or directly accessed. If the file was directly accessed, the debug_backtrace() function will return an empty array. You can use this to conditionally execute code, similar to how you would use name == “main” in Python.

Can I use

name == “main” in PHP to test my code?

While there isn’t a direct equivalent of name == “main” in PHP, you can still test your code. PHP has a rich set of testing tools like PHPUnit that you can use to write unit tests for your code. You can also use the debug_backtrace() function to conditionally execute code, which can be useful for testing.

What is the purpose of using

name == “main” in Python?

The main purpose of using name == “main” in Python is to control the execution of your code. When the Python interpreter reads a source file, it first sets a few special variables like name, and then executes all of the code found in the file. If the name variable is set to “main“, it means that the module is being run standalone by the user and we can execute appropriate code.

Can I use

name == “main” in other programming languages?

The name == “main” construct is specific to Python. However, many other programming languages have similar constructs. For example, in Java, you can use the main method to execute code when the class is run directly.

How can I check if a PHP script is being run directly or included in another script?

You can use the debug_backtrace() function in PHP to check if a script is being run directly or included in another script. If the script is being run directly, the debug_backtrace() function will return an empty array.

What is the debug_backtrace() function in PHP?

The debug_backtrace() function in PHP generates a backtrace, which is a list of all the function calls made up to the point where debug_backtrace() is called. This can be used to check if a script is being run directly or included in another script.

Can I use

name == “main” in PHP to control the execution of my code?

While there isn’t a direct equivalent of name == “main” in PHP, you can still control the execution of your code. You can use the debug_backtrace() function to check if a script is being run directly or included in another script, and then conditionally execute code based on this.

Harry FuecksHarry Fuecks
View Author

Harry Fuecks is the Engineering Project Lead at Tamedia and formerly the Head of Engineering at Squirro. He is a data-driven facilitator, leader, coach and specializes in line management, hiring software engineers, analytics, mobile, and marketing. Harry also enjoys writing and you can read his articles on SitePoint and Medium.

Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form