Autoloading Classes/Namespaces

Today we are going to discuss everything about classes and namespaces autoloading 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 (Comming Soon)

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. Lets 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

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(Coming Soon) 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(Coming Soon) 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. Lets 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.

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_classes

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. Also you can follow us on twitter to get more information and updates.

Thanks.

Comments (0)

POST
Author Supun Kavinda
395 7