Suppose you have multiple PHP classes in a folder and you have to include or require these classes in order to use them. But there is an easy way to load them –
The spl_autoload_register()
function automatically loads a class when an object of the class is created.
So this function doesn’t load any class unnecessarily, when you create an object of a class only then it will load that class.
Let’s see an example of the spl_autoload_register() function
Important – One rule you have to follow in order to achive the calss autoload functionality. The rule is that the Class Name and the File name must be the same. For example – Class name = MyClass{}
then file name = MyClass.php
.
The following image is the strcuture of the php-test
folder where inside the classes
folder there are three classes and we will see how we can automatically load these classes inside the index.php
file.

<?php
class Main{
public function sayHello(){
echo "Hello From Main.";
}
}
<?php
class Test{
public function sayHello(){
echo "Hello from Test.";
}
}
<?php
class MyClass{
public function sayHello(){
echo "Hello from MyClass.";
}
}
The spl_autoload_register(callback)
take a callback function as a parameter and this callback function also has a parameter that give us the name of the class, so we called this parameter $class_name
.
<?php
spl_autoload_register(function($class_name){
require __DIR__."/classes/$class_name.php";
});
$obj = new Test();
echo $obj->sayHello();
echo "\n";
$obj2 = new Main();
echo $obj2->sayHello();
Hello from Test.
Hello From Main.
What if a class doesn’t exist?
If you create an object of a class that does not exist in the path you define, then it will give you a not found error.
You can easily handle this error by checking whether the class file exists.
<?php
spl_autoload_register(function($class_name){
$path = __DIR__."/classes/";
$theClass = "{$path}{$class_name}.php";
if(file_exists($theClass)) return require $theClass;
exit("Error: The \"{$class_name}\" class not found in {$path} || Or check your spelling.");
});
$obj = new Test();
echo $obj->sayHello();
echo "\n";
$obj2 = new Mains();
echo $obj2->sayHello();
Hello from Test.
Error: The "Mains" class not found in C:\xampp\htdocs\php/classes/ || Or check your spelling.