I was checking out a WordPress plugin and I saw this function in the constructor of a class:
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();
Here’s a sample code:
class Hello{
function __construct(){
add_action('init', array($this, 'printHello'));
}
function printHello(){
echo 'Hello';
}
}
$t = new Hello;
From your sample code,
$this->printHello()
will not work outside of yourclass 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.