在回调期间调用类函数中的外部对象

时间:2011-05-10 作者:Dor Zuberi

我有一个类,它有一个在数据库中检查和创建表的函数。为了做到这一点,我需要使用WordPress$wpdb对象。

我需要只在第一次激活插件时运行该函数,因此我使用该函数:

register_activation_hook  ( __FILE__, array( \'MemorialCandles\', \'dbInstall\'   ) );
问题是,我总是会遇到以下错误:

致命错误:当不在/home/xxx/xxx/wordpress/wp-content/plugins/memorialcands/memorialcands中的对象上下文中时,使用$this。班php第77行

the class code:

<?php

// Global Variables:
global $wpdb;
register_activation_hook  ( __FILE__, array( \'MemorialCandles\', \'dbInstall\'   ) );

/**
 * Class: MemorialCandles
 * 
 * Provides skeleton to the plugin and handles queries and action.
 * 
 * @author Dor Zuberi <[email protected]>
 * @copyright 2011 Dor Zuberi
 * @license http://www.php.net/license/3_01.txt
 */
class MemorialCandles
{
    // Variables    
    /**
     * @var string stores plugin direction - RTL or LTR.
     */
    private $pluginDirection;

    /**
     * @var string stores the plugin database table name.
     */
    private $tableName;

    // Constructor
    /**
     * Initiates the plugin, stores and configure the basic setup procedures.
     * 
     * @return void
     */
    function __construct()
    {
        global $wpdb;

        $this->tableName = $wpdb->prefix . \'memorialcandles\';
    }

    // Getters

    // Setters

    // Methods
    /**
     * Handles the database table creation.
     * 
     * @return void
     */
    function dbInstall()
    {
        global $wpdb;

        if( $wpdb->get_var( "SHOW TABLES LIKE `{$this->tableName}`" ) != $this->tableName )
        {
            $sql = "CREATE TABLE `{$this->tableName}` (
                        id        int(8) NOT NULL AUTO_INCREMENT,
                        fullName  text   NOT NULL,
                        message   text   NOT NULL,
                        postDate  text   NOT NULL,
                        galleryID int(8) NOT NULL,

                        UNIQUE KEY id(id)
                    );";

            require_once( ABSPATH . \'wp-admin/includes/upgrade.php\' );
            dbDelta( $sql );
        }
    }

    /**
     * Handles the database table drop procedure.
     * 
     * @return void
     */
    function dbUninstall()
    {
        global $wpdb;

        $sql = "DROP TABLE IF EXISTS `{$this->tableName}`;";

        $wpdb->query( $sql );
    }    
}

?>
提前感谢!:D

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

尝试:

register_activation_hook  ( __FILE__, array( new MemorialCandles(), \'dbInstall\'   ) );
或者将dbInstall定义为“static”,并使用它来设置表名,而不是构造函数,我认为这是最好的方法。

SO网友:Bainternet

好的,新答案,这次是一个经过测试的工作解决方案。首先创建类的实例,然后调用register_activation_hook 比如:

$MemorialCandles = NEW MemorialCandles();

register_activation_hook  ( __FILE__, array( \'MemorialCandles\', \'dbInstall\'   ) );

结束