php spl_autoload_register()不加载类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php spl_autoload_register()不加载类相关的知识,希望对你有一定的参考价值。

我有一个index.php需要通过qazxsw poi测试1类。在Test 1类中,需要具有相同自动加载的Test2类,但发生以下错误:

致命错误:DOMDocument :: registerNodeClass():类Test2不存在于...

我试着看看自动加载是否能够编写spl_autoload_register()并且效果很好。因此,通过其他测试,我意识到使用$test2 = new Test2();自动加载不包含Test2类文件。

有没有人可以帮助我?

Test1.php

registerNodeClass()

Test2.php

<?php

namespace Test;

use TestTest2;

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

?>

的index.php

<?php

namespace Test;

class Test2 extends DOMElement
{

//bla, bla, bla...

}

?>

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

<?php

require_once('./autoload.php');

use TestTest1;

$html = 'something';

$test = new Test1($html);

?>
答案

class <?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 FooBarBazQux class * from /path/to/project/src/Baz/Qux.php: * * new FooBarBazQux; * * @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; } }); ?> 在命名空间Test2中,所以为了做Test你必须在命名空间new Test2()中,或者你可以指定完全限定名(即Test)来实例化类。

当你调用new TestTest2()时,DOMDocument会对以下内容产生影响:

$this->dom->registerNodeClass('DOMElement', 'Test2');

并且它找不到$extendedClass = 'Test2'; $obj = new $extendedClass(); ,因为该代码不是从Test2命名空间调用的。因此,您需要传递完全限定的类名(w / namespace)。

使用:Test

以上是关于php spl_autoload_register()不加载类的主要内容,如果未能解决你的问题,请参考以下文章

PHP中spl_autoload_register函数的用法

php spl_autoload_register() 函数

php的spl_autoload_register函数的一点个人见解

php spl_autoload_register()不加载类

php命名空间+spl_autoload_register实现类的自动加载

PHP自动加载上——spl_autoload_register