因为 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']);