php spl_autoload_register() 不加载类

标签 php class domdocument autoload spl-autoload-register

我有一个 index.php 需要 Test1 类槽 spl_autoload_register() 。在 Test1 类中,Test2 类需要具有相同的自动加载,但发生了此错误:

Fatal error: DOMDocument::registerNodeClass(): Class Test2 does not exist in...

我尝试查看自动加载是否可以编写 $test2 = new Test2(); 并且运行良好。因此,通过其他测试,我意识到 registerNodeClass()自动加载不包含 Test2 类文件。

有谁可以帮助我吗?

Test1.php

<?php

namespace Test;

use Test\Test2;

class Test1
{
    function __construct($html)
    {
        $this->dom = new \DOMDocument();
        @$this->dom->loadHTML($html);
        $this->dom->registerNodeClass('DOMElement', 'Test2');
    }
}

?>

Test2.php

<?php

namespace Test;

class Test2 extends \DOMElement
{

//bla, bla, bla...

}

?>

index.php

<?php

require_once('./autoload.php');

use Test\Test1;

$html = 'something';

$test = new Test1($html);

?>

autoload.php(与 Facebook 用于 php-sdk 的相同)

<?php
/**
 * An example of a project-specific implementation.
 * 
 * After registering this autoload function with SPL, the following line
 * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
 * from /path/to/project/src/Baz/Qux.php:
 * 
 *      new \Foo\Bar\Baz\Qux;
 *      
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'Test\\';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});
?>

最佳答案

class Test2 位于命名空间 Test 内,因此为了执行 new Test2() 您必须位于命名空间 Test 内 或者您可以指定完全限定名称(即new Test\Test2())来实例化该类。

当您调用 $this->dom->registerNodeClass('DOMElement', 'Test2'); 时,DOMDocument 会执行以下操作:

$extendedClass = 'Test2';
$obj = new $extendedClass();

并且它找不到 Test2,因为该代码不是从 Test 命名空间调用的。 因此,您需要传递完全限定的类名(带命名空间)。

使用:$this->dom->registerNodeClass('DOMElement', 'Test\Test2');

关于php spl_autoload_register() 不加载类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800928/

相关文章:

php 调用父函数使父函数无法加载自己的变量

PHP 简单 DOMDocument 抓取排除 td 类

php - 在 Centos 8 上使用 ODBC 17 和 Laravel 连接到 SQL Server 时出现 SSL 错误 'dh key is too small'

C++ 将对象传递给函数

php - 使用 join 和两个 where 条件更新语句

java - 检查类名不应包含特定文本

php - 将 HTML 文本转换为 Leet (1337) Speak with XPath

带有特定标记的 PHP DOM html 问题

php - 加载剥离 javascript 并将其放入数组中供以后使用的替代方法是什么

php - 交换 php 中找到的数组键