使用SPL_AUTLOAD_REGISTER加载类

时间:2015-04-20 作者:Getenburg

我在“includes”文件夹中加载类时遇到问题。在几个WP安装上进行了尝试,结果总是一样的。

我制作了一个简单的插件,以查看问题是否存在于其他地方,但由于未知原因,它再次失败。

插件文件夹名称test

test.php

<?php
/*
Plugin Name: test
Plugin URI: test
Description: 
Version: 1.0
Author: test
Author URI: test
*/

class test_main {
    public function __construct() {
        include_once( \'includes/autoloader.php\' );
    }   
}

new test_main();
然后在includes 文件夹我有两个文件,其中一个是autoloader,另一个是water类,如果加载了它,它应该会杀死它。

autoloader.php

<?php
class autoloader {
    public function __construct() {
        spl_autoload_register( array( $this, \'auto_load_classes\' ) );
    }

    public function auto_load_classes( $class_name ) {
        if ( is_readable( plugin_dir_path( dirname( __FILE__ ) ) . \'includes/\' . $class_name . \'.php\' ) )
        {
            include_once( plugin_dir_path( dirname( __FILE__ ) ) . \'includes/\' . $class_name . \'.php\' );
        }
    }
}

new autoloader();

water.php

<?php
class water {
    public function __construct() {
        die( \'water\' );
    }
}

new water();
water 类从未加载,为什么?

echo $class_name;
在中autoloader.php 返回值:一
<?php
class water {
    public function __construct() {
        die( \'water\' );
    }
}

new water();

我去检查了几个插件,看看是否有人在使用这个设置,我能找到的唯一一个插件是WooCommerce,它们的设置基本上与上面的设置相同,但对我来说它失败了。有人有什么想法吗?

编辑

好吧,这很尴尬,表明一个人应该多睡一会儿:)new water(); 应在加载程序外部调用,因为加载程序不应实例化该类。new water(); 在本例中应调用test.php 文件之后new test_main();. 那就好了。

1 个回复
最合适的回答,由SO网友:Getenburg 整理而成

对,回答我自己的愚蠢。

spl_autoload_register 在实例化类时调用。

移动new water(); 来自文件water.php 到文件test.php 解决了问题。

测试。php应该如下所示:

<?php
/*
Plugin Name: test
Plugin URI: test
Description: 
Version: 1.0
Author: test
Author URI: test
*/

class test_main {
    public function __construct() {
        include_once( \'includes/autoloader.php\' );
    }   
}

new test_main();

new water();

结束

相关推荐

Loop for sticky posts

我用过Justin Tadlock\'s 关于如何创建仅包含粘性帖子的循环的教程。代码大致如下所示:$sticky = get_option( \'sticky_posts\' ); rsort( $sticky ); $sticky = array_slice( $sticky, 0, 2 ); query_posts( array( \'post__in\' => $sticky, \'caller_get_posts\' => 1 ) ); 根据教程,我