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();

Read More

Here’s a sample code:

class Hello{
  function __construct(){
    add_action('init', array($this, 'printHello'));
  }
  function printHello(){
    echo 'Hello';
  }
}
$t = new Hello;

Related posts

1 comment

  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.

Comments are closed.