[英]call different namespace or class from one in PHP
在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
我的代码有什么问题?
当我在__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();
您还应该注意,不建议使用__autoload
。 您现在应该使用spl_autoload_register()
。 有关自动加载的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.