【问题标题】:call different namespace or class from one in PHP在 PHP 中调用不同的命名空间或类
【发布时间】:2014-09-30 06:51:42
【问题描述】:

index.php我有以下代码

require 'Bootstrap.php';
require 'Variables.php';

function __autoload($class){
    $class = str_replace('Control\\', '', $class);
    require_once 'class/'.$class.'.php';
}

$bootstratp = new Control\Bootstrap();

Bootstrap.php

namespace Control;
class Bootstrap{
  function __construct(){
    Constructor::load_html();
    self::same_namespace_different_class();
  }
  static function same_namespace_different_class(){
    Variables::get_values();
  }
}

class/Constructor.php

class Constructor{
  static function load_html(){
    echo 'html_loaded';
  }
  static function load_variables(){
     echo 'load variables';
  }
}

Variables.php

namespace Control;
class Variables{
    static function get_values(){
        Constructor::load_variables();
    }
}

假设,我总共有 4 个 PHP 文件,包括 2 个不同命名空间的 3 个 Class 文件。我在index.php 上还有一个__autoload 函数,它将调用“类”文件夹中的类,但我的“控制”命名空间文件位于根文件夹中。

当我在 __autoload 中回显类名时,即使我从全局命名空间调用一个类,我也会得到所有以“Control\”开头的类名。

我遇到了错误

Warning: require_once(class/Variables.php): failed to open stream: No such file or directory in _____________ on line 10

我的代码有什么问题??

【问题讨论】:

    标签: php class namespaces autoload bootstrapping


    【解决方案1】:

    当我在 __autoload 中回显类名时,即使我从全局命名空间调用一个类,我也会得到所有以“Control\”开头的类名。

    这是因为在Bootstrap.php 中,所有代码都在Control 命名空间(namespace Control)中。所以当你使用时:

    Variables::get_values();
    

    你打电话

    \Control\Variables::get_values();
    

    如果你想使用全局命名空间中的Variables,你应该在这里使用:

    \Variables::get_values();
    

    当然,Variables.php 文件中也会发生同样的情况:

    Constructor::load_variables();
    

    由于构造函数是在全局命名空间中定义的(class/Constructor.php 中没有使用命名空间),你应该在这里使用:

    \Constructor::load_variables();
    

    如果仍然不清楚,您还可以查看有关 namespaces in PHP. 的这个问题

    您还应该注意到,不建议使用__autoload。你现在应该使用spl_autoload_register()Documentation about autoloading

    【讨论】:

    • Marcin,非常感谢,太棒了,速度很快,
    • 有没有办法调用全局命名空间而不在自动加载函数中添加行$class = str_replace('Control\\', '', $class);
    • @yellowandred 事实上,你应该保持你的自动加载功能不变——只有require_once 'class/'.$class.'.php';应该在那里,在其他类中,如果你想使用全局类,你应该在类名之前使用``命名空间,正如我在回答中向您展示的那样。如果类位于自动加载器的全局命名空间中,则不应从类中删除命名空间,因为如果您在不同的命名空间中有类,则会导致严重问题。这样做也是不好的做法。
    猜你喜欢
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多