我之前发布了一些关于在 PHP 中使用命名空间的问题,从我得到的信息来看,我下面的这个示例代码应该可以工作。
但是,当我尝试像这样在 PHP 中使用命名空间时出现错误。这是按原样运行以下代码时的第一个错误…
Fatal error: Class 'Controller' not found in E:\Controllers\testing.php on line 6
E:\Controller\testing.php 文件
<?php
use \Controller;
include('testcontroller.php');
$controller = new Controller;
$controller->show();
?>
E:\Controller\testcontroller.php 文件
<?php
use \Library\Registry;
namespace Controller
{
class Controller
{
public $registry;
function __construct()
{
include('E:\Library\Registry.class.php');
$this->registry = new Registry;
}
function show()
{
echo $this->registry;
echo '<br>Registry was ran inside testcontroller.php<br>';
}
}
}
?>
E:\Library\Registry.class.php 文件
<?php
namespace Library\Registry
{
class Registry
{
function __construct()
{
return 'Registry.class.php Constructor was ran';
}
}
}
?>
正如你所看到的,我试图让它尽可能简单,只是为了让命名空间部分正常工作。我尝试了不同的变体,但似乎无法弄清楚。
原文由 JasonDavis 发布,翻译遵循 CC BY-SA 4.0 许可协议
即使使用
use
语句,您也需要指定您尝试实例化的类的命名空间。这里有很多例子: http ://www.php.net/manual/en/language.namespaces.importing.php为了更好地理解它,我将向您描述它是如何工作的。在您的情况下,当您执行
use \Controller
时,整个Controller
命名空间对您可用,但此命名空间中的类不可用。因此,例如:另一个例子:
测试控制器.php:
测试.php:
如果您希望准确导入
Controller
类,您需要执行use Controller\Controller
- 那么这个类将可以在您当前的范围内访问。