Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Janos Antal
Janos Antal
1,451 Points

autoload - spl_autoload_register (), how this codepart works?

Dear Gentlemen,

Could someone help me to explain how this codepart works? Is this autoload is the same as __autoload?

function autoload($class) {                     

        if (file_exists('core/libs/' . $class . ".php")) {          

            require 'core/libs/' . $class . ".php";                 
        } else {

            exit ('Shit Happened: The' . $class . '.php is missing (core/libs/).');
        }
    }

    spl_autoload_register("autoload");

As I understood from function tutorials: somewhere we should get data for this $class argument to get this working, or not? Because there is nothing else in the code related to this function and it works properly.

Thank you for help.

1 Answer

The function:

function autoload($class) {
//code
}

Loads a class file that was referenced in your PHP script. This function basically tells PHP what directories to search in to find the classes in your PHP script and once these classes are found it will use the require() function to include those files. Defining the autoload() function is not enough, you must tell PHP to use this function to search for classes and to do this you must register this function as an Autoloader:

spl_autoload_register("autoload");

The spl_autoload_register() function tells PHP to use this function to autoload classes. Your PHP script can have several autoloaders, so the spl_autoload_register() function allows you to register several autoloaders if necessary. In this case you are registering a single autoloader called "autoloader".

Janos Antal
Janos Antal
1,451 Points

Thanks! I just do not understand one thing, is this working like a cycle? Cycles through the given library searching for files which are including any $class-es?