PHP - Using the __autoload function

Introduction

Defining a function named __autoload tells PHP that the function is the autoloader.

You could implement an easy solution:

function __autoload($classname) { 
   $lastSlash = strpos($classname, '\\') + 1; 
   $classname = substr($classname, $lastSlash); 
   $directory = str_replace('\\', '/', $classname); 
   $filename = __DIR__ . '/' . $directory . '.php'; 
   require_once($filename); 
} 

Here we keep all PHP files in src folder.

Our __autoload function tries to find the first occurrence of the backslash \ with strpos.

And then extracts from that position until the end with substr.

Finally, we concatenate the current directory, the class name as a directory, and the .php extension.

<?php 

     use Bookstore\Domain\Book; 
     use Bookstore\Domain\Customer; 

     function __autoload($classname) { 
        $lastSlash = strpos($classname, '\\') + 1; 
        $classname = substr($classname, $lastSlash); 
        $directory = str_replace('\\', '/', $classname); 
        $filename = __DIR__ . '/src/' . $directory . '.php' 
        require_once($filename); 
     } 

     $book1 = new Book("2018", "C", 0003, 12); 
     $customer1 = new Customer(5, 'John', 'Doe', 'a@mail.com'); 

__autoload function has to be defined only once, not in each file.

Related Topic