【问题标题】:PHP default spl autoload function do not load parent of class in namespacePHP 默认 spl 自动加载功能不会在命名空间中加载类的父类
【发布时间】:2017-04-05 14:43:16
【问题描述】:

我无法在命名空间中自动加载类的父类。不继承子类被加载;但孩子无法自动加载父类。

文件结构:

/index.php
/lib/router.php
/lib/ns1/parent1.php
/lib/ns1/child1.php

index.php:

spl_autoload_extensions(".php");
spl_autoload_register();
require '/lib/router.php';

/lib/router.php

$child1 = new ns1\child1();

/lib/ns1/child1.php

namespace ns1;
class child1 extends parent1 {}

/lib/ns1/parent1.php

namespace ns1;
class parent1 { function __construct() {} }

当我从 child1 中删除“扩展”部分时,一切正常。 使用“扩展”部分我有错误:

致命错误:spl_autoload(): Class parent1\child1 无法加载到 /lib/ns1/child1.php 中

有没有办法通过内置的默认 spl 自动加载功能来做到这一点? 非常感谢您的帮助。

【问题讨论】:

  • parentreserved word,它可能只是一个例子,但如果它是一个坏的例子
  • 当然这只是示例:) 名称是为了更好地理解。但我纠正它...

标签: php class namespaces parent autoload


【解决方案1】:

我在这个答案中找到了适合我的解决方案 https://stackoverflow.com/a/7987085/5208203

只需将 set_include_path() 添加到文件 index.php:

set_include_path(get_include_path().PATH_SEPARATOR."/lib");
spl_autoload_extensions(".php");
spl_autoload_register();
require '/lib/router.php';

但我不确定性能,可能只是我在类定义中遇到的另一个失败的解决方法...

【讨论】:

    猜你喜欢
    • 2014-12-07
    • 2013-07-19
    • 1970-01-01
    • 2015-08-23
    • 2021-06-29
    • 2013-09-07
    • 2012-09-05
    • 2013-06-01
    • 2012-10-22
    相关资源
    最近更新 更多