我不知道如何解释,但我会尽力。好的,我有这三个文件:
主题.php
path: /shared/models/Theme.php class: Theme namespace: namespace models;
自定义.php
path: /themes/default/Custom.php class: Custom namespace: this class does not use namespace
设置.php
path: /controllers/Settings.php class: Settings namespace: this class does not use namespace
在我的Settings.php
中看起来像:
<?php
class Settings
{
public function apply()
{
$theme = new \models\Theme();
$theme->customize(); // in this method the error is triggered
}
}
现在,看看下面的Theme
类:
<?php
namespace models;
class Theme
{
public function customize()
{
$ext = "/themes/default/Custom.php";
if (file_exists($ext))
{
include $ext;
if (class_exists('Custom'))
{
$custom = new Custom();
//Here, $custom var in null, why???
}
}
}
}
当我执行代码时,出现以下错误:
Message: require(/shared/models/Custom.php) [function.require]: failed to open stream: No such file or directory
Line Number: 64
为什么解释器尝试从另一个目录加载 Custom
类,而不是使用 $ext
var 指定?
最佳答案
当在 \models
命名空间中的类内部调用 new Custom()
时,您实际上是在尝试实例化 \models\Custom
。既然您说您的 Custom
类“没有命名空间”,请尝试使用 new\Custom()
来代替。
您收到的错误似乎来自某些类自动加载器,它尝试为 \models\Custom
请求类文件,但失败了。
关于php - 将对象实例化为具有命名空间的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14310568/