PHP: Running a class directly, or include/require it without changing the code

August 29, 2011

Lately, i was writing a class in php, and i wanted to test it from the command line. In the same file i wrote the class in, i put this:

$test = new Test();

that’s the default way to do this in php. What’s not so interesting about this, is that when you want to use the class in another project and you include the file, the class will automatically be called, because that piece of code is in there. So you’ll have to edit your file again.

That’s not what i wanted.

What i want is to make the class file detect if it’s being included/required or not, and act in a correct manner: if the file is not included by another file the class should be called automatically, when it is included though, it should not, so that the project that includes the class can do whatever they want with it. And i want all of this without ever having to change the code in the class file.

The following code does just that:

//initiate the class if we're not included by another php file
if (basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
$test = new Test();
//you can put other code here, e.g:
$test->monkey();
}

it compares the basename of the __FILE__ constant, with the basename of the $_SERVER[‘PHP_SELF’] environment variable. __FILE__ always returns the name of the real file in which it is called, while PHP_SELF returns the path of the file that was directly called by the user (so if it’s called in a file that’s being included, it returns the path of the parent file). If both are the same, the file is not included or required by another file, so the class should be called.

That’s all šŸ™‚

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: