Hi everyone,
Edit: If you are a beginner, check out the complete autoloading tutorial.
Today we are going to discuss some advanced stuff in PHP: Autoloading Classes and Namespaces. If you don’t have a piece of good knowledge of classes and namespaces I would suggest you learn them first here.
This tutorial is based on the following tutorial i wrote to Hyvor’s developer site. Visit it to see the complete reference on Autoloading classes and namespaces
Lets start!
Most of the developers who are 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 like following.
include('dog.php');
include('cat.php');
include('cow.php');
include('goat.php');
include('fox.php');
The concept “Autoloading” comes to solve this problem.
Autoloading Classes
Mainly there are two ways to define a autoload function.
-
spl_autoload_register
function (Highly recommended) -
__autoload
function
Following code 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;
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. 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.
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();
The super autoload function
It’s pretty simple to create a autoload function that is usable in sub directories which can include classes as well as namespaces.
<?php
spl_autoload_register(function($className) {
$className = str_replace("\", DIRECTORY_SEPARATOR, $className);
include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';
});
If you are interested in understanding how it works, please visit our original tutorial.
Happy webmastering!
Supun Kavinda,
Moderator,
000webhost.