⊗ppOpNsCA 107 of 107 menu

Custom Function for Autoloading Classes in OOP in PHP

Often, the default autoloader may not suit you for some reasons. In such a case, you can write your own autoloader.

To do this, you need to pass your written callback function as the first parameter to the function spl_autoload_register. This function will be called when PHP detects an attempt to use an unloaded class. The name of the class with its namespace will be passed as a parameter to this function:

<?php spl_autoload_register(function($class) { // the variable $class will contain the class name with the namespace }); ?>

And the function's responsibility is to load this class via require based on the class name. That is, inside this function, we must define our own rule for loading classes, i.e., our own naming convention.

Let's write an example of our own autoloader. Suppose, for example, we state that the path to the class file from the site root will be the same as the namespace, but preserving the case of characters.

That is, if we have a class Core\Admin\PageController, then the path to it should be Core/Admin/PageController.php.

As you can see, to transform the class name with its namespace, you just need to change backslashes to forward slashes, and add .php to the class name. Let's do that:

<?php spl_autoload_register(function($class) { $filename = str_replace('\\', '/', $class) . '.php'; require($filename); }); ?>

However, we will get a relative path to the file (relative to the site root). It's better to make an absolute path, like this:

<?php spl_autoload_register(function($class) { $root = $_SERVER['DOCUMENT_ROOT']; $filename = $root . '/' . str_replace('\\', '/', $class) . '.php'; require($filename); }); ?>

There is another nuance. In different operating systems, the folder path separator can be a forward slash or a backslash. Let's make our code independent of the operating system. To do this, instead of a forward slash for separating paths, we will use the constant DIRECTORY_SEPARATOR, which contains the correct slash for the operating system on which our script is currently running. As a result, we get the following code:

<?php spl_autoload_register(function($class) { $root = $_SERVER['DOCUMENT_ROOT']; $ds = DIRECTORY_SEPARATOR; $filename = $root . $ds . str_replace('\\', $ds, $class) . '.php'; require($filename); }); ?>

Test the autoloader function I created.

Come up with your own autoloading rule and implement it.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline