Autoloading PHP classes that use namespaces

This is a basic tutorial on autoloading 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:

In the PHP code above, I 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:

In our autoloader function:

  1. 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.
  2. 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.
  3. 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!

Facebook Comments