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

标签 php class namespaces instance

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

  • 主题.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/

相关文章:

c# - 如何将对象从一个方法初始化为类中的另一个方法?

c++ - 在命名空间的结构中使用静态函数时出错。 (c++)

php - Laravel 日志对多对多关系的修订

php - 如何裁剪图像以具有 1 :1 aspect ratio CSS

javascript - ScriptManager 不可访问

PHP:如何使用::而不是\访问命名空间类?

namespaces - 在 Laravel 5 中获取应用程序命名空间

PHP Get 方法不起作用

php - 基于 CSS :root variables 动态生成 add_theme_support( 'editor-color-palette') 颜色

css - 如何使用 CSS 设置 HTML 样式?