This is a guide on how to autoload PHP classes that use namespaces.
The problem with namespaces is that they contain backslashes. As a result, we need to be able to handle these backslashes inside our autoloading function.
Our namespace class.
Let us take a look at an example of a PHP class that uses a namespace.
<?php namespace ThisInterestsMe; class Test{ function __construct() { echo 'Success!'; } }
In the PHP code above, we created a class called Test that uses the namespace ThisInterestsMe.
Inside the constructor, it prints out the word “success”. Note that I have saved this class as Test.php inside a folder called classes.
Autoloading our namespace class.
Now, let’s autoload the class we just created.
<?php //Our autoloader function. function autoloader($className){ //Split the class name up if it contains backslashes. $classNameParts = explode('\\', $className); //The last piece of the array will be our class name. $className = end($classNameParts); //Include the class. include 'classes/' . $className . '.php'; } //Tell PHP what our autoloading function is. spl_autoload_register('autoloader'); //Instantiate our object. $test = new ThisInterestsMe\Test();
In our autoloader function:
- We broke the class name up into an array. To do this, we split the string using PHP’s explode function. We used the backslash as a delimiter.
- The name of our class will always be the last element in the array. To get the last element of a PHP array, you can use the end function.
- Finally, we included the class file using the last element of our array.
This function will also work with classes that do not use namespaces. If no backslashes are present in the string, then our array will only contain one element. The end function will return this element because technically-speaking, it is still the last element in our array.
If you run the code above, you should be greeted by the “Success!” message that we echo inside our object’s constructor.
Hopefully, you found this guide to be useful!