【问题标题】:Classes autoload using namespaces for parent and children使用父子名称空间自动加载类
【发布时间】:2013-11-19 02:40:03
【问题描述】:

我阅读了几篇关于在 php 中使用命名空间的文章,但我还没有明白。我有 3 个文件:

script.php 和 dog.php 位于同一个根文件夹,abstr。动物类.php位于cls文件夹中,狗扩展了动物。

来源: cls/Animals.php:

namespace cls;
abstract class Animals { .. }

Dog.php(没有命名空间,因为它位于根文件夹中):

 class Dog extends Animals {...}

script.php:

function __autoload($cls){
     $file = str_replace('\\',DIRECTORY_SEPARATOR,$cls).".php";
    if(file_exists($file)){
        require_once $file;
    } else {
        throw new Exception("File not found: ".$file);
    }
}

$dog = new Dog("German Shepard");

但我得到 Not found exception 用于类 Animals 和 $file 只是 Animals.php 没有命名空间......

  1. 谁能告诉我如何获取命名空间并将其包含在__autoload 函数的路径中?

  2. 或者对父子节点使用相同的命名空间会更好吗?

  3. 据我了解,正确的命名空间 = 文件位置?

【问题讨论】:

    标签: php namespaces autoload


    【解决方案1】:

    如果 Dog 不在 'cls' 命名空间中,您必须为 Animals 类编写完整的限定名:

    class Dog extends \cls\Animals { ... }
    

    【讨论】:

      猜你喜欢
      • 2016-07-01
      • 1970-01-01
      • 2017-11-03
      • 2021-06-29
      • 2013-09-07
      • 2011-09-09
      • 2013-05-16
      • 2013-11-30
      相关资源
      最近更新 更多