Autoload classes from different folders

前端 未结 12 996
不知归路
不知归路 2020-11-28 19:35

This is how I autoload all the classes in my controllers folder,

# auto load controller classes
    function __autoload($class_name) 
    {
             


        
12条回答
  •  忘掉有多难
    2020-11-28 19:54

    You should name your classes so the underscore (_) translates to the directory separator (/). A few PHP frameworks do this, such as Zend and Kohana.

    So, you name your class Model_Article and place the file in classes/model/article.php and then your autoload does...

    function __autoload($class_name) 
    {
        $filename = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class_name)).'.php';
    
        $file = AP_SITE.$filename;
    
        if ( ! file_exists($file))
        {
            return FALSE;
        }
        include $file;
    }
    

    Also note you can use spl_autoload_register() to make any function an autoloading function. It is also more flexible, allowing you to define multiple autoload type functions.

    If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

    Edit

    Note : __autoload has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged. Please refer to PHP documentation for more details. http://php.net/manual/en/function.autoload.php

提交回复
热议问题