DEV Community

Keramot UL Islam
Keramot UL Islam

Posted on • Originally published at Medium on

1 1

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay