PHP Autoloading Class Files

Summary: in this tutorial, you will learn how to organize your class files and load them automatically using PHP  __autoload() function.

php autoload classIt is good practice to keep each PHP class in a separated file and all class files in a folder named classes. In addition, the name of the class should be used to name the file for example if you have a Person class, the file name should be person.php.

Before using a class you need to load it in your script file using PHP include file function such as  require_once() as follows:

When the number of classes grows, it is quite tedious to call  require_once() function everywhere you use the classes. Fortunately, PHP provides a mechanism that allows you to load class files automatically whenever you try to create an object from a non-existent class in the context of the current script file.

PHP will call  __autoload() function automatically whenever you create an object from a non-existent class. To load class files automatically, you need to implement the __autoload() function somewhere in your web application as follows:

Whenever you create an object from a non-existent class, PHP looks into the  ./classes folder and load the corresponding class file using the  require_once() function.

From now on, you don’t have to call  require_once() function every time you use the class, which is very useful.

Notice that if PHP cannot find the __autoload() function or if the  __autoload() function failed to load the class files, you will get an error message.

You can download the script files of this tutorial via the following link:

[Download not found]

 

  • Was this tutorial helpful ?
  • YesNo