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


Instantiate an object into a class with namespace

我不知道该怎么解释,但我会尽力的。好的,我有这三个文件:

  • 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指定?

'models命名空间的类中调用new Custom()时,您实际上正在尝试实例化'models'Custom。既然你说你的Custom类"没有命名空间",那就试试new 'Custom()吧。

你得到的错误似乎是来自一些类自动加载器,试图要求'models'Custom类文件和失败。