Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么要使用数组($this,';function';)而不是$this->;函数()_Php_Arrays_Wordpress_Class - Fatal编程技术网

Php 为什么要使用数组($this,';function';)而不是$this->;函数()

Php 为什么要使用数组($this,';function';)而不是$this->;函数(),php,arrays,wordpress,class,Php,Arrays,Wordpress,Class,我在查看WordPress插件时,在一个类的构造函数中看到了这个函数: add_action('init', array($this, 'function_name')); 我搜索并发现数组($this,'function\u name')是一个有效的回调。我不明白的是:为什么要使用这个方法,而不是使用$this->function_name() 下面是一个示例代码: class Hello{ function __construct(){ add_action('init', a

我在查看WordPress插件时,在一个类的构造函数中看到了这个函数:

add_action('init', array($this, 'function_name'));
我搜索并发现
数组($this,'function\u name')
是一个有效的回调。我不明白的是:为什么要使用这个方法,而不是使用
$this->function_name()

下面是一个示例代码:

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

从示例代码中,
$this->printHello()
在您的
类Hello
之外不起作用。传递对当前对象的引用($this)和方法的名称将允许外部代码调用对象的给定方法