Autoload classes from different folders

前端 未结 12 995
不知归路
不知归路 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:48

    Altough this script doesn't have the name convention and this thread is already a bit old, in case someone is looking of a possible answer, this is what I did:

    function __autoload($name) {
        $dirs = array_filter(glob("*"), 'is_dir');
    
        foreach($dirs as $cur_dir) {
            dir_searcher($cur_dir, $name);
        }
    
    }
    
    function dir_searcher($cur_dir, $name) {
    
        if(is_file("$cur_dir/$name.php")) {
            require_once "$cur_dir/$name.php";
        }
    
        $dirs = array_filter(glob($cur_dir."/*"), 'is_dir');
        foreach($dirs as $cdir) {
            dir_searcher("$cdir", $name);
        }
    }
    

    not sure if it is really optimal, but it searches through the folders by reading dir recursively. With a creative str_replace function you can get your name cenvention.

提交回复
热议问题