PHP Class autoloader

abmsourav

Keramot UL Islam

Posted on December 5, 2019

PHP Class autoloader

php classes autoload

When I first heard about PHP class autoloader, I thought “I might be a huge mechanism”.

But in reality, class autoload is a very simple thing and it’s just a function.

Earlier we used __autoload() function but now it is deprecated on PHP 7.2. So we’ll use spl_autoload_register()

function my_autoloader($class) {
    include 'classes/' . strtolower( $class ) . '.php';
}

spl_autoload_register('my_autoloader');

It will load all the classes from the project. But what if, we want to load specific classes, which are in the /classes folder?

“We need to use namespace for those classes.”

function my_autoloader($class) { 
    if ( false === strpos( $class, __NAMESPACE__ ) ) { 
        return; 
    }

    $class_name = preg_replace( '/^' . __NAMESPACE__ . '\\\/', '', $class );

    require_once __DIR__ . '/classes/' . strtolower( $class_name ) . '.php';
} 
spl_autoload_register(__NAMESPACE__.'\my_autoloader');

Source Code

💖 💪 🙅 🚩
abmsourav
Keramot UL Islam

Posted on December 5, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

PHP Class autoloader
automation PHP Class autoloader

December 5, 2019