問題描述
我想創(chuàng)建一個(gè)監(jiān)聽器類
class Listener {
var $listeners = array();
public function add(callable $function) {
$this->listeners[] = $function;
}
public function fire() {
foreach($this->listeners as $function) {
call_user_func($function);
}
}
}
class Foo {
public function __construct($listener) {
$listener->add($this->bar);
}
public function bar() {
echo 'bar';
}
}
$listener = new Listener();
$foo = new Foo($listener);
但是此代碼失敗并出現(xiàn)此錯(cuò)誤:
But this code fails with this error:
注意:未定義的屬性:18 行 index.php 中的 Foo::$bar
Notice: Undefined property: Foo::$bar in index.php on line 18
可捕獲的致命錯(cuò)誤:傳遞給 Listener::add() 的參數(shù) 1 必須是可調(diào)用的,給定 null,在第 18 行在 index.php 中調(diào)用并在第 5 行定義了 index.php
Catchable fatal error: Argument 1 passed to Listener::add() must be callable, null given, called in index.php on line 18 and defined index.php on line 5
我做錯(cuò)了什么?
推薦答案
在 PHP 5.4 之前,沒有名為
callable
的類型,所以如果將它用作類型提示,則表示名為callable
的類".如果您使用 PHP >= 5.4,callable
是一個(gè)有效的提示.Before PHP 5.4, there was no type named
callable
, so if you use it as a type hint, it means "the class namedcallable
". If you use PHP >= 5.4,callable
is a valid hint.可調(diào)用對(duì)象由描述可調(diào)用對(duì)象名稱的字符串(例如函數(shù)名或類方法名)或數(shù)組指定,其中第一個(gè)元素是對(duì)象的實(shí)例,第二個(gè)元素是要調(diào)用的方法的名稱.
A callable is specified by a string describing the name of the callable (a function name or a class method name for example) or an array where the first element is an instance of an object and the second element is the name of the method to be called.
對(duì)于 PHP <5.4、替換
For PHP < 5.4, replace
public function add(callable $function)
與:
public function add($function)
調(diào)用它:
$listener->add(array($this, 'bar'));
這篇關(guān)于在 PHP 中將實(shí)例方法作為參數(shù)傳遞的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!