Загрузка...

PHP autoloading explained

What is autoloading?
In a PHP project we might need to include multiple external files. Generally, we use include or require function to include these external files.

This is a tedious task to include hundred and thousand of external files like this.

Imagine we have a system that can include these external files in our current file automatically. Yes, it is possible. The system is called autoloading.
How to use autoloading?
When PHP parser has seen a class for the very first time, it includes the class into the current file using function spl_autoload_register().
Can we have an example, please?
Sure. Let's explain with an example.

At the top of our file we have used the function spl_autoload_register(). It contains an anonymous function as a parameter. Again that anonymous function contains a class name as a parameter. Finally, the same class name is included.
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});

Now, we are creating two objects of two different classes Test1 and Test2. See these two classes are not included manually anywhere. When PHP parser sees these functions for the first time, it checks whether spl_autoload_register function is available and it found. Then it included these two classes in the current file, provided the classes should be available within the project folder, anywhere.
$obj = new Test1();
$obj2 = new Test2();

So, the conclusion is, instead of including many files individually, PHP's autoloading features include all the files which are used in the current file using function spl_autoload_register().

Видео PHP autoloading explained канала PHP Explained
Яндекс.Метрика

На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.

Об использовании CookiesПринять