1

我试图了解 WordPress 如何与动作、类和方法一起工作。

如果有一个类“TestClass”并且它有一个公共方法“method1”

该方法可以与任何操作挂钩,如“add_action('theHook', ['TestClass', 'method1']);”

据我了解。如果不初始化类,就不能访问它的公共方法和对象。现在,我假设 WordPress 必须遵循这一点,并且它必须初始化我的“TestClass”,这将导致 public __construct() 触发。

但是,经过测试,它不会触发 __construct()..

为什么是这样?。我知道解决方法是在“method1”内部进行自我初始化,但我试图弄清楚为什么 WordPress 会这样。

4

1 回答 1

1

因为 WordPress 将您的方法称为静态函数:TestClass::method()

有多种解决方案:

1.添加Action前初始化类

在添加操作之前初始化您的类,如下所示:

$test = new TestClass();
add_action('hook', [$test, 'method']);

2.在你的类中调用钩子:

class TestClass {
    public function __construct() {
        // Your construct
    }
    public function method() {
        // Your Method
    }

    public function call_hook() {
        add_action('hook', [$this, 'method']);
    }
}

$test = new TestClass();
$test->call_hook();

3. 使用单例

如果你只需要一个类的实例并在不同的地方调用它,你必须看看Singleton 设计模式

示范:

class MySingletonClass {

    private static $__instance = null;
    private $count = 0;
    private function __construct() {
        // construct
    }

    public static function getInstance() {
        if (is_null(self::$__instance)) {
            self::$__instance = new MySingletonClass();
        }
        return self::$__instance;
    }

    public function method() {
        $this->count += 1;
        error_log("count:".$this->count);
    }
}

$singleton = MySingletonClass::getInstance();
add_action('wp_head', [$singleton, 'method']);


$singleton2 = MySingletonClass::getInstance();
add_action('wp_footer', [$singleton2, 'method']);
于 2020-10-27T06:59:45.947 回答