Autoloader



We used to use the classes we created in our previous topics by including them with require . The disadvantage of such a use is the necessity to be included in other classes required for a class. For this reason, we will show how to do this in a more practical way in this section and make the inclusion process directly to the program itself. We will use spl_autoload_register () in PHP to do this. This function is called when a non-object class is invoked. 

 

 

# Creation of the tokenizer


We will use the spl_autoloader_register () method to create the autoloader

File: autoloader.php
<?php 

spl_autoload_register(function(string $class)
{
    $path = str_replace('\\', '/', $class) . '.php';

    if( is_file($path) )
    {
        require $path;
    }   
});

The above function is to automatically include the calling class. The str_replace () function creates the class's path information by converting it to the \ symbol / symbol in the namespace if the calling class contains namespace .

 

 

# Using the tokenizer


We include the autoloader classes we create in the file we call.

File: index.php
<?php require 'autoloader.php';

$automobile = new Automobile;

echo $automobile->wayType();
Highway

As far as the above usage is concerned, we have now been able to automatically load the Automobile :: class with the top class Vehicle :: without including require.