jump to navigation

Using the PHP 5 Autoloading Classes Feature to Automatically Include PHP Files March 30, 2011

Posted by Tournas Dimitrios in PHP.

Autoload is a new feature introduced in PHP5 that you don’t have to explicitly require or include a PHP script file that contains the class being used any more but it will be automatically loaded or included when needed. For example, with PHP4 you would have to write something like this:
require_once(“Myclass.php”) ; // Myclass.php contains our class with the name “Myclass”
$obj = new Myclass // Instantiating a new object of the class

Now imagine a large project where many objects have to be instantiated from classes , that would be very tedious repeated process  .Every time you had to create an instance of some class , you had to include the particular PHP file that contains that class. It is not just extra work but also make it more error-prone. It can be a challenge to manage the whole lot of include or require lines as well. That’s where the autoload feature of PHP5 kicks in. Instead of including a particular PHP script every time we need it, we create a very simple function at the beginning of the current file so that PHP automatically knows what file to include when we need a particular class. For example:
function __autoload($class_name) {

require_once ‘classes/’. $class_name. ‘.php’;}

$obj1 = new MyClass1() ; // PHP automatically requires ‘classes/MyClass1.php’

$obj2 = new MyClass2() ; // PHP automatically requires ‘classes/MyClass1.php’

As illustrated by the example above,  you will never have to explicitly include any PHP scripts again. Instead, you will specify the place to look for the corresponding script file to include and PHP will do the task for you. In this example, the name of the class “MyClass1” is passed to the function __autoload as variable $class_name and in the body of the function, it specifies the location of the exact PHP file to include, namely, in the ‘classes’ directory and the name of the file is the same as that of the class, $class_name. ‘.php’.

Usually, the __autoload function should be placed in a site wide configuration file which is included at the beginning of all PHP files of your website so it will only be written once. This way, all the classes of your website or application can be better named and organized.



1. test - April 16, 2011

you guys sucks correct function for php5.3 is

function __autoload($class_name) {
require_once(“classes/”. $class_name. “.php”);

tournasdimitrios1 - April 16, 2011

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s