Posted on Leave a comment

[Ultimate] Guide to PHP Autoload

Calling spl_autoload_register without argument

  • spl_autoload_register() without arguments will invoke (call) another function called spl_autoload when php script tries to access an unknown class. The name of the unknown class will be passed to spl_autoload. spl_autoload first then find if there is a file name identical to the class name (lower and upper case, php 7) with the extension .php or .inc in: First, the include path then the local directory. The search will stop once the file is found (not when the class is found). Sounds confusing? Let me demonstrate:

Let’s make it clearer:

So, I have the root folder with two files: index.php and cat.php (lowercase C). One folder called animal that contains Cat.php (uppercase)

Here are the code in each file:

cat.php

<?php

class Cat
{
    function __construct($name)
    {
        echo "I am a cat in the local directory";
    }
}

Cat.php (inside animal folder)

<?php

class Cat
{
    function __construct($name)
    {
        echo "I am the cat in the ANIMAL directory";
    }
}

index.php (root folder)

<?php

set_include_path(get_include_path() . PATH_SEPARATOR . "animal");
spl_autoload_register();

$x = new Cat("jane");

When I access the index.php file in the browser, here is what I get:

As you can see, the Cat inside animal is used. It is because of this line in the index.php file

set_include_path(get_include_path() . PATH_SEPARATOR . "animal");

I set the animal to the include path. PHP will search for file names with extensions .php or .inc in those paths first. If the file name is found (in this case is Cat.php/Cat.inc/cat.php/cat.inc), then the search will stop. Remember that the search doesn’t care if the class exists. It only cares if the file exists. If I comment out the implementation of the Cat class in animal/Cat.php and access the index.php again, I’ll get an error:

Fatal error: Uncaught Error: Class ‘Cat’ not found in C:\xampp\htdocs\lab\oop\index.php:6 Stack trace: #0 {main} thrown in C:\xampp\htdocs\lab\oop\index.php on line 6

Now, if I comment out the set_include_path line in index.php, I’ll get the Cat class in the root directory:

// set_include_path(get_include_path() . PATH_SEPARATOR . "animal");
spl_autoload_register();

$x = new Cat("jane");
Leave a Reply

Your email address will not be published. Required fields are marked *