将对象实例化为具有命名空间的类

时间:2013-01-14 02:14:35

标签: php class namespaces instance

我不知道如何解释,但我会尽我所能。好的,我有这三个文件:

  • Theme.php

    path: /shared/models/Theme.php
    class: Theme
    namespace: namespace models;
    
  • Custom.php

    path: /themes/default/Custom.php
    class: Custom
    namespace: this class does not use namespace
    
  • 的settings.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指定?

1 个答案:

答案 0 :(得分:3)

new Custom()命名空间中的类内部调用\models时,您实际上正在尝试实例化\models\Custom。由于您说Custom类没有名称空间“,请尝试使用new \Custom()

你得到的错误似乎来自某个类自动加载器,它试图要求\models\Custom的类文件并失败。