Pavi
Pavi

Reputation: 1739

why use array($this,'function') instead of $this->function()

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;

Upvotes: 5

Views: 737

Answers (1)

maxhb
maxhb

Reputation: 8865

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.

Upvotes: 2

Related Questions