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 GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay