core error

__autoload() in PHP

Posted on: 26/07/2011

What

__autoload()  is a function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet.

Why

This is very useful for removing the need of making a long list of includes at the beggining of each script so we can use the classes inside those files.

How

you can create an autoloader.php file with:

function __autoload($class_name) {
    include str_replace('_','/',$class_name) . '.php';
}

This file can be included in the main php file (i.e. the index.php of an MVC) so it gets included in all the php scripts in the application. Therefore we could do:

$c1 = new controllers_c1;
$m2 = new models_services_profiles;

As you can see, we can create a model of class profiles without including the file models/services/profiles.php since it is autoloaded by the autoloader php when the class was not found in the first place.

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


    • Justin Cooney: Great comic, this made me laugh!
    • Justin Cooney: Interesting, I didn't know about the Google App Engine, I'm glad I found your article on it!

    Categories

    %d bloggers like this: