Banner of

Creating A Real Website with PHP object oriented - part 4 - Autoload and Register Classes

Category: php

Date: August 2020
Views: 778

Every php file you create must be included at some point before you use it. but as the website becomes bigger and the number of files increases, it becomes extremely difficult to keep track of the files. if you can't organize your code you might find yourself including the same file multiple times. and the code itself will look ugly and might not be resources friendly

In this tutorial we will introduce the concept of autoloading and registring classes only when needed. A class file will be included only when we are trying to instansiate it by creating an object from it. The include procedure will be neat and elegant. all because of the php function spl_autoload_register. IT was introduced since PHP 5.1 . it takes a function as a parameter, this function will hold the include statements we need. and returns true on success otherwise it returns false.

First we define our autoload function, it is in this part of our code that our class files naming convention will become helpful, as it will simplify the process of including the files. as we decided earlier all our class files will be either in "classes" or "views" directories. so the included file will look like :


Autoloading And registring classes with spl_autoload_register

//index.php file:
function myautoloader($classname){
    $fname = "sources/classes/$classname.class.php";
        include_once $fname;
        return true;
    $fname = "sources/views/$classname.class.php";
        include_once $fname;
        return true;
    return false;

With this code; we will no longer worry about including any class file in any part of our project. we can even use any class in any other class and it will be loaded and registred as I illustrated in the following video:


Previous Article Next Article

0 Comments, latest

No comments.