⊗ppOpNsAu 105 of 107 menu

Autoloading Classes in OOP in PHP

You already know that to use any class, we must include it via require. When a project has a lot of classes, it results in many includes, which are very inconvenient to write and difficult to manage.

To solve this problem, PHP added autoloading of classes. Autoloading allows PHP to automatically load the file with a class when attempting to access that class in the code. However, classes won't load just like that - they must be placed in the site's folders in a special way, following some convention for naming class files and folders. You can use the built-in PHP convention, or come up with your own and use it.

Let's start with the standard PHP convention. This convention means that if we have a file with a class, then the path through the site's folders to this file must match the file's namespace, and the file name must match the name of the class stored in it. Furthermore, the folder and file names must be in lowercase.

Let's look at an example. Suppose we have the following class:

<?php namespace Core\Admin; class PageController { } ?>

According to the convention, this class should be located in the folder /core/admin/ in the file pagecontroller.php.

Now let's use our class in the file index.php, without including it via require, but using autoloading. To do this, at the beginning of the file where classes are called, you should call the function spl_autoload_register. Let's do it:

<?php spl_autoload_register(); // enable autoloading $obj = new Core\Admin\PageController; // calmly create an object ?>

In the file index.php, enable automatic loading of classes. Following the convention for naming folders and files, create the class Core\User, the class Core\Admin\Controller and the class Project\User\Data. In the file index.php, create objects of these classes.

azbydeenesfrkakkptruuz