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

I was looking through the WordPress plugin and I saw this function in the class constructor:

add_action('init', array($this, 'function_name'));

I searched and found what array($this, 'function_name')is a valid callback. I do not understand: why use this method instead of using$this->function_name();

Here is a sample code:

class Hello{
  function __construct(){
    add_action('init', array($this, 'printHello'));
  }
  function printHello(){
    echo 'Hello';
  }
}
$t = new Hello;
+4
source share
1 answer

From your sample code $this->printHello()will not work outside of yours class Hello. Passing a reference to the current object ($ this) and the method name will allow the external code to call this method of your object.

+1
source

Source: https://habr.com/ru/post/1622440/


All Articles