【问题标题】:Instantiate an object into a class with namespace将对象实例化为具有命名空间的类
【发布时间】:2013-01-14 02:14:34
【问题描述】:

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

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

【问题讨论】:

    标签: php class namespaces instance


    【解决方案1】:

    \models 命名空间中的类内部调用new Custom() 时,实际上是在尝试实例化\models\Custom。既然您说您的 Custom 类“没有命名空间”,请改用 new \Custom()

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

    【讨论】:

    • 是的,你完全正确。记住这一点非常重要:Since you say your Custom class "has no namespace", try new \Custom() instead. 非常感谢 :)
    猜你喜欢
    • 2019-05-12
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    相关资源
    最近更新 更多