Auto-Loading classes in PHP

Back to getting up to speed on PHP. This is a quick snippet of code that’ll probably come in handy: –

<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

This will auto-load a php file with the class name requested when the class is used. Assuming the naming standard is followed correctly this will be a handy little shortcut

 

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: