命名空间
ThinkPHP5 采用命名空间方式定义和自动加载类库文件,有效的解决了多模块和
Composer 类库之间的命名空间冲突问题,并且实现了更加高效的类库自动加载机制。
特别注意的是,如果你需要调用PHP内置的类库,或者第三方没有使用命名空间的类库,
记得在实例化类库的时候加上 \ ,例如:
// 错误的用法
$class = new stdClass();
$xml = new SimpleXmlElement($xmlstr);
// 正确的用法
$class = new \stdClass();
$xml = new \SimpleXmlElement($xmlstr);
在ThinkPHP 5.0 中,只需要给类库正确定义所在的命名空间,并且命名空间的路径与类库
文件的目录一致,那么就可以实现类的自动加载,从而实现真正的惰性加载。
例如, \think\cache\driver\File 类的定义为:
namespace think\cache\driver;
class File
{
}
如果我们实例化该类的话,应该是:
$class = new \think\cache\driver\File();
系统会自动加载该类对应路径的类文件,其所在的路径是
thinkphp/library/think/cache/driver/File.php 。