我正在学习创建一个WP插件作为一个类。然而,在调用我的函数时,add\\u操作似乎不起作用;它在使用$this->init()时工作。
示例:
    class test
{
    public $age = NULL;
    public function __construct()
    {
        //register an activation hook
        register_activation_hook( __FILE__, array( &$this, \'installplugin\' ) );
        add_action(\'init\', array( &$this, \'init\' ) ); //this doesn\'t work
        //$this->init(); //This WORKS!
    }
    function installplugin()
    {
        add_option( \'age\', 45 );
        $this->init();  
    }
    function init()
    {
        $age = get_option( \'age\' );
        $this->age = $age;
    }
    function printAge(  )
    {
        echo "The age is " . $this->age . "<br />";
    }
}
 因此,运行后:
$learnObj =  new learnable_test();
$learnObj->printAge();
 它只打印:“年龄是”
但是如果我没有注释掉add\\u操作(\'init\',…)然后使用$this->init(),这似乎可行,打印“年龄是45”
我错过了什么?
 
                    最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成
                    嗯,它不能也不会像你想要的那样工作。
让我们看看你到底在做什么。
在构造函数中,您有:
add_action(\'init\', array( &$this, \'init\' ) ); //this doesn\'t work
 所以你加上
init 对象到WPs的方法
init 钩WP运行时
init 行动,然后你的
init 方法将运行到,但不早也不晚。
然后你可以这样做:
$learnObj =  new learnable_test();
$learnObj->printAge();
 所以您创建了类的对象。它将添加
$learnObj->init 至WPs
init 钩
如果您在WPs之后调用这两行init 钩子已经做了,什么都不会发生。
如果你以前给他们打过电话(我想是的),你的$learnObj->init 将在WPs期间执行init 行动(和age 将设置变量)。
但在第二行,你想访问这个age 变量这里还没有设置,因为WP还没有执行init 行动$learnObj->init 也没有被执行。