OOP PHP Lesson 4 – __autoload() function

featured image for php oop basics - a red flower photo

Reasonable approach to class definition storage is to keep every class definition in a separate file. However, if we have many classes, the need to include every file at the beginning of a php code can be headache. Moreover, sometimes we don’t know which class definition files are needed, or make decision not to use some classes. To solve this problem, in PHP OOP programming we have special useful function: void __autoload ( string $class ) with class name as an argument. The function is called automatically every time you want to use class not defined yet.

Now, instead annoyance of including all class definition files, we can use this function in our main program file, as listed below, and __autoload will try to load suitable class file when needed:

function __autoload($classname) {

   $classfile = "./". $classname .".php";
   require_once($classfile);

}

$a_customer = new Customer();
$a_customer->set_name("Steven");
$a_customer->get_name();
$a_customer->say_hello();

unset($a_customer);

Customer.php file is left intact. We replaced require(‘Customer.php’); with:

function __autoload($classname) {

   $classfile = "./". $classname .".php";
   require_once($classfile);

}

After main program file is properly modified, we should get the same output like in Lesson 3.