Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Autoload classes in PHP

Thursday, November 1st, 2012 by Servage

In PHP you must include all relevant scripts in the script being executed. Normally you have one entry point – e.g. index.php – which in turn loads all required scripts and figures out dependencies. This often results in too much – or in cases of errors, too little being loaded. The problem mainly is a product of you being in charge of manually loading required stuff somehow. For example by figuring out which requests need which classes and the use the PHP include or require functions to fetch it.

Wouldn’t it be great if this is done for you? Actually PHP has a built-in handler to auto-load classes. This does not work for functions or other scripts, but at least your class dependencies could be obsolete :-) It works in a way, that you define an autoload-handler. Whenever PHP tries to instantiate a non-existing class, it runs the auto-load function, and tries again. An error is only thrown if the class is still non-existing after the autoloader was run.

Static example

function __autoload($class) {

	$files = array(
		'MyClass' => 'path/to/MyClass.php',
	);

	if (array_key_exists($class, $files))
		require($files[$class]);
}

In the example above the autoloader tries to find the attempted class name in a predefine array, which in turn maps the class name to a PHP file to be included. This is good if you want to avoid to much “magic” going on, like checking for file existing etc. If performance is a non-issue, take a look at the dynamic example below.

Dynamic example

function __autoload($class) {

	$file = 'path/to/classes/'.$class.'.php';

	if (file_exists($file))
		require($file);
}

In the dynamic example above, the class name is used to generate an expected class name, and load it – if existing. This requires more IO and makes it harder to handle different directories etc. for class-files – but appears more convenient than the static example above.

Read more about autoloading in the PHP docs.

Autoload classes in PHP, 5.0 out of 5 based on 2 ratings
Categories: Guides & Tutorials

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.