【问题标题】:How can I use one class inside another with the same namespace?如何在具有相同命名空间的另一个类中使用一个类?
【发布时间】:2012-09-12 08:58:10
【问题描述】:

我在我的项目中使用 spl_autoload,但是当我尝试以下代码时,它给了我这个错误:

致命错误:在

中找不到类“Router\Route”

//路由器文件

<?php
namespace Router;
class Router{
function foo(){
new Route();
}
?>

//路由文件

<?php
namespace Router;
class Route{}
?>

有什么帮助吗?我对命名空间有点陌生。

【问题讨论】:

  • 不确定是否可以多次声明同一个命名空间。如果你想使用命名空间。说“使用名称空间名称”。
  • 您能告诉我们您的 spl_autoload_register 函数吗?
  • 我正在使用默认的自动加载功能“spl_autoload_register('spl_autoload')”

标签: php class namespaces autoload spl


【解决方案1】:

您可以使用来自另一个命名空间的类,但不能有两个同名的命名空间(这不符合这一点)。

// In one file.
namespace Router;
class Router{
  function foo(){
    use Route as r;
    new r\Route();
  }
}

// In another file.
namespace Route;
class Route{}

【讨论】:

  • 这两个类都在同一个命名空间中。
  • 所以它不存在在我的目录结构中反映这些命名空间的方法吗?我在“路由器”目录中有路由器和路由,所以我的 spl 自动加载会在这个命名空间中搜索它们。有没有办法做到这一点?
猜你喜欢
  • 2016-02-06
  • 2012-05-27
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
相关资源
最近更新 更多