I was checking out a WordPress plugin and I saw this function in the constructor of a class:
我正在检查一个WordPress插件,我在一个类的构造函数中看到了这个函数:
add_action('init', array($this, 'function_name'));
I searched and found that array($this, 'function_name')
is a valid callback. What I don't understand is: why use this method, instead of using $this->function_name();
我搜索并发现数组($ this,'function_name')是一个有效的回调。我不明白的是:为什么要使用这种方法,而不是使用$ this-> function_name();
Here's a sample code:
这是一个示例代码:
class Hello{
function __construct(){
add_action('init', array($this, 'printHello'));
}
function printHello(){
echo 'Hello';
}
}
$t = new Hello;
1 个解决方案
#1
1
From your sample code, $this->printHello()
will not work outside of your class Hello
. Passing a reference to the current object ($this) and the name of a method will allow the external code to call the given method of your object.
从您的示例代码中,$ this-> printHello()将无法在您的类Hello之外工作。传递对当前对象($ this)的引用和方法的名称将允许外部代码调用对象的给定方法。
#1
1
From your sample code, $this->printHello()
will not work outside of your class Hello
. Passing a reference to the current object ($this) and the name of a method will allow the external code to call the given method of your object.
从您的示例代码中,$ this-> printHello()将无法在您的类Hello之外工作。传递对当前对象($ this)的引用和方法的名称将允许外部代码调用对象的给定方法。