如何在自动加载中使用PHP名称空间? [英] How do I use PHP namespaces with autoload?
本文介绍了如何在自动加载中使用PHP名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试使用自动加载和命名空间时出现此错误:
I get this error when I try to use autoload and namespaces:
严重错误:在上的/usr/local/www/apache22/data/public/php5.3/test.php 中找不到类"Class1" >第10行
Fatal error: Class 'Class1' not found in /usr/local/www/apache22/data/public/php5.3/test.php on line 10
有人可以告诉我我在做什么错吗?
Can anyone tell me what I am doing wrong?
这是我的代码:
Class1.php:
Class1.php:
<?php
namespace Person\Barnes\David
{
class Class1
{
public function __construct()
{
echo __CLASS__;
}
}
}
?>
test.php:
<?php
function __autoload($class)
{
require $class . '.php';
}
use Person\Barnes\David;
$class = new Class1();
?>
推荐答案
Class1不在全局范围内.
Class1 is not in the global scope.
请参见下面的工作示例:
See below for a working example:
<?php
function __autoload($class)
{
$parts = explode('\\', $class);
require end($parts) . '.php';
}
use Person\Barnes\David as MyPerson;
$class = new MyPerson\Class1();
修改(2009-12-14):
仅需澄清一下,我对"use ... as"的使用是为了简化示例.
Just to clarify, my usage of "use ... as" was to simplify the example.
替代方法如下:
$class = new Person\Barnes\David\Class1();
或
use Person\Barnes\David\Class1;
// ...
$class = new Class1();
这篇关于如何在自动加载中使用PHP名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文