Skip to content

PHP Programming

How to Use the PHP 5 Autoloading Classes Feature to Automatically Include PHP Files

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("foo.php"); // foo.php contains the class Foo

myFoo = new Foo();

Every time you need to create an instance of some class you have 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, with the simple function highlighted in bold, 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.

For state-of-the-art PHP web hosting, Rackspace Cloud has proven itself countless times by over delivering again and again. Read these cloud hosting reviews to know why they stand out.

Article Source:

Be Sociable, Share!
    The following two tabs change content below.

    Latest posts by Ray (see all)

    Add Your Comment (Get a Gravatar)