php学习bug总结

1.浏览器提示:

Fatal error: Class '\core\lib\drive\log\file' 
not found in /Library/WebServer/Documents/imooc/core/lib/log.php on line 22

仔细检查这个文件缺失存在,然后查看调用创建类的地方代码,
并打印

$class = '\core\lib\drive\log\\'.$drive;p($class);

self::$class = new $class;

创建类的时候,
也$class打印 \core\lib\drive\log\file
路径也是对的.但是就是调试不出来.
仔细检查发现 file文件的命名空间写成了\core\lib\log
修改成\core\lib\drive\log就没有问题了

这里为什么可以使用命名空间的方法来new 一个类呢? 难道不需要判断有没有这个文件或者有没有导入么? 看第二个TIPS;

2.这里学习一个常识吧,在php类中new 一个类
第一,需要导入这个文件,这里可以使用spl_autoload_register指定一个调用方法.自动load一个类.

spl_autoload_register('\core\imooc::load');

这段代码表示当new一个类的时候,会自动导入这个类.具体代码如下:将命名空间的\替换成路径的/写法.去导入文件路径.

static public function load($class){
        //自动加载类库
        if(isset($classMap[$class])){
            return true;
        }else{
            $class = str_replace('\\','/',$class);

            $file = IMOOC.'/'.$class.'.php';
            ///Library/WebServer/Documents/imooc/core/route.php

            if(is_file($file)){
                include $file;
                self::$classMap[$class] = $class;
            }else{
                //throw "没有找到文件";
                return false;
            }

        }
        p('load ok');

 }

第二:所以当new 一个类的时候按照命名空间写法,会自动触发spl_autoload_register这个指定的加载方法.
可以这样写

$route = new \core\lib\route;

也可以这样写:

$route = new \core\lib\route();

你可能感兴趣的:(php学习bug总结)