DEV Community

loading...

PHP Class autoloader

Keramot UL Islam
WordPress Enthusiast. Loves PHP, and JavaScript.
Originally published at Medium on ・1 min read

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

Discussion (0)