Register Your Own Autoload Functions

PHP has a few in-built magic method __get(), __set(), __sleep(), _toString() etc. These functions are all really useful but they are not used very often in your day-to-day development, but one magic method is really useful this is the ** _autoload() function**. This function is automatically called each time you try to instantiate a class but the class can not be found. When you normally call a class to use in your code you will do something like this.

// include the file for the class
include_once 'MyClass.php';
include_once 'OtherClass.php';

// instantiate the class
$class = new MyClass();
$class2 = new OtherClass();

This fine if your just using one class, but there could be times in your script where you have to reference lots of different classes, this is when using an autoload function is perfect. The __autoload function will be called when you instantiate the class and will pass in the class name as the parameter to the function. If you are using good PHP coding practice the file should be called the same as your class name, or be prefixed with something. This means that you will be able to find the file you need just from the class name.


<?php
function __autoload($classname) {
    $filename = $classname . ".php";

    if(file_exists( $filename ))
    {
        include_once($filename);
    }
}

$class = new MyClass();
$class2 = new OtherClass();
?>

But the problem with this function is that it can only be defined once in your application so if you, like many others store their classes in a neat folder structure you will need to come up with a naming structure to use this function. For example you could prefix the new of the class with the folder structure, so if the class is inside folder you will name the class FolderOne_FolderTwo_MyClass(). Then in your autoload function you can explode the class name on the underscores and work out the file structure from the class name. But this isn't very flexible and your class names could become huge, to solve this problem there is another function that you can use to register you own autoload functions. Using spl_autoload_register() can define your own function which will be used just like the __autoload() function, the benefit of this is that it will allow you to define multiple autoload functions. This allows you to create an autoload function for each of your namespaces if needed.


function my_own_autoloader($class) {
    include 'classes/' . $class . '.php';
}

spl_autoload_register('my_own_autoloader');

function another_autoloader($class) {
    include 'controllers/' . $class . '.php';
}

spl_autoload_register('another_autoloader');

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring