如题,我看到在一些yii2的写法中命名空间是可以被直接加载的,比如:
<code> namespace web\models;
use Yii;
use web\classes\CPost;
//... code ...
$post = new CPost;</code>在以上 web\models 命名空间中,CPost对象是可以直接用new关键词创建的,
但我自己单独做了命名空间的测试如下:
<code> namespace web\models;
// include "../classes/CPost.php"; 这句必须取消注释才不报错
use web\classes\CPost;
class MPost {
public function run(){
echo "MPost->run()被调用";
}
public function getClassFunc(){
$class = new CPost;
$class->run(); //报错,提示找不到 web\classes\CPost对象
}
}
$post = new MPost;
$post->getClassFunc(); </code>在测试代码中,如果不inlucde CPost文件的话就会报错,
但Yii2全程未引入文件,仅用命名空间就能直接新建对象。
请问这是怎么回事,又是如何做到的?
如题,我看到在一些yii2的写法中命名空间是可以被直接加载的,比如:
<code> namespace web\models;
use Yii;
use web\classes\CPost;
//... code ...
$post = new CPost;</code>在以上 web\models 命名空间中,CPost对象是可以直接用new关键词创建的,
但我自己单独做了命名空间的测试如下:
<code> namespace web\models;
// include "../classes/CPost.php"; 这句必须取消注释才不报错
use web\classes\CPost;
class MPost {
public function run(){
echo "MPost->run()被调用";
}
public function getClassFunc(){
$class = new CPost;
$class->run(); //报错,提示找不到 web\classes\CPost对象
}
}
$post = new MPost;
$post->getClassFunc(); </code>在测试代码中,如果不inlucde CPost文件的话就会报错,
但Yii2全程未引入文件,仅用命名空间就能直接新建对象。
请问这是怎么回事,又是如何做到的?
spl autoload,顺便去学下composer
查看一下 composer.json 文件内容,里面有 autoload 这一项,看看是不是定义了整个目录自动加载还是仅仅是几个文件。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号