Autoloading Classes with Namespaces in PHP

Update: Check out my complete PHP Autoloading Tutorial

Today we are going to discuss everything about autoloading classes and namespaces in PHP. However, before you start you must have a basic knowledge on PHP classes. If not, we prefer you to follow our tutorial on Object Oriented Programming with PHP.

At the end, you will learn

What is Autoloading?

Most of the developers working with OOP(Object Oriented Programming) tends to save each class definition in a separate file. In this case, developers face a big problem. They have to include lots of files at the beginning of the document. Let's consider the following example.

Consider you are going to use several classes that are saved in separated files in your root directory.

Then create index.html in your root directory and add following code


<?php

$dog = new dog();


Fatal Error: Class "dog" not found

You'll get the above error because any programming language doesn't find class files and include them by itself. So, you have to include all the class files before you call the class. (Usually it's included at the beginning of the document)

But, when including files developers face below shown problem. If they use 10 classes they have to include all the class files at the beginning.


<?php
include('dog.php');
include('cat.php');
include('cow.php');
include('goat.php');
include('fox.php');


When your project grows day-by-day it may need to include 100 class files in a document. How can a developer do that in lot of documents without making a mistake? It's impossible! To solve this problem the autoload function comes!

Autoloading

Mainly there are two ways to define a autoload function.

  1. spl_autoload_register function (Highly recommended)
  2. __autoload function
spl_autoload_register is strongly recommended to use because of it's flexibility. The __autoload function is discouraged and will be deprecated soon. Let's see how to use it and how it works.

This will register autoload function and will try to load class files


<?php

spl_autoload_register(function($className) {
	include_once $className . '.php';
});

$dog = new dog();
$cat = new cat();

// static_methods below
echo cow::getToken();
echo fox::$name;


Step By Step...

Think about the time the code new dog(); is executed. Then PHP calls the callback function. "dog" is sent as the parameter ($className). Then "dog.php" is included.

How To Organize Your Classes Like a PRO

How does an experienced programmer organize their class files? They use some simple tricks. Here is a simple and powerful file structure


/ 
	ajax
	inc
	class 
		class1.php
		class2.php
		class3.php
	css
	js 
	images


Simply, save all the class files in a folder in the root ("class" is recommended as the folder name).
Then create your powerful autoload function.


<?php

spl_autoload_register(function($className) {
	include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';
});


Explained...

Now, you can use your classes anywhere in your website with PHP! However, you have to use a different method when implementing an autoload function in a subdomain. Check out our tutorial on it.

Important! You must save the class files with the name of the class. Otherwise this trick won't work.

Autoloading Namespaces

Autoloading namespaces is an interesting topic. By the introduction of namespaces in PHP 5.3 PHP developers could encapsulate their items and it made handling scripts easy. However, we only discuss about how to autoload namespaces here. If you need to learn more about namespaces please visit our tutorial on it. Let's learn how to autoload namespaces. First of all we have to learn the use of namespaces.

When a website becomes larger, it's harder to keep all the class files in a same directory. Also we have to use very long names for files and classes, such as animal_dog_dog1_addName. It is a really bad practice. Namespaces are introduced to prevent this problem. Let's see how it works!

By using namespaces you can save your classes in sub folders. The file of the class name can be saved in /class/dog as well as /class/cat. Here is the file structure.


class
	animals
		dog.php
		cat.php
		goat.php
	birds
		owl.php
		peacock.php
	pets
		dog.php
		cat.php
	mainClass1.php
	mainClass2.php
	mainClass3.php


In above file structure you can understand, different files with the same name can be saved in different locations (folders). Namespaces are based on this simple logic. Now the problem is how to autoload them? Here is how namespaces are called with PHP.

	
<?php

spl_autoload_register(function($className) {
	include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';
});

$dog = new animal\dog(); 
$cat = new animal\cat();


// static functions
animal\cat::name();
animal\cat::appearance();


Step By Step...

	
<?php

spl_autoload_register(function($className) {

	$className = str_replace("\\", DIRECTORY_SEPARATOR, $className);
	include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';

});	


Explained...

At The End

Here are some tips.

If you have any questions comment below. We are always here to help you.

Thanks.

Tagged: PHP
Liked the article? Follow me on Twitter, or help Hyvor grow by funding Hyvor Talk.
Latest on Hyvor Developer
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Image for All About MYSQLI Prepared Statements in PHP
All About MYSQLI Prepared Statements in PHP
Image for Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image for PHP Contact Form - The Email Method
PHP Contact Form - The Email Method
Image for The Best Way to Perform MYSQLI Prepared Statements in PHP
The Best Way to Perform MYSQLI Prepared Statements in PHP
Related Articles
568