[英]PHP: assign function to class method
如何在PHP中的類中為方法分配函數? 我嘗試了以下方法:
class Something{
public function __construct(){
$functionNames = array('foo', 'bar')
$variable = 'blablabla';
foreach($functionNames as $functionName){
if(method_exists($this, $functionName))
continue;
$this->{$functionName}() = function($params){ //should create the methods "foo" and "bar"
echo $variable; //should echo 'blablabla' (I know that the variable was declared outside this function, but how can I access it anyway?)
}; //the error points to here
}
}
}
但是這段代碼給了我這個錯誤:
Fatal error: Can't use method return value in write context
有誰知道如何將匿名函數分配給類方法,同時還能夠訪問該函數之外的變量?
你正在做foreach($functionNames as $functionName){
這意味着$functionName
是一個字符串 ,而不是一個數組。 所以,不要使用$functionName[0]
。
method_exists
需要2個參數。 一個是對象,另一個是方法名稱。 它應該是:
method_exists($this, $functionName)
至於創建函數,你不需要在=
的左側使用 ()
。 它應該是:
$this->$functionName = function($params) use($variable){
echo $variable;
};
需要use($variable)
來告訴PHP在函數內部使用該變量。 這就是閉包在PHP中的工作方式,它與其他語言不同。
所以,你的課應該是這樣的:
class Something{
public function __construct(){
$functionNames = array('foo', 'bar');
$variable = 'blablabla';
foreach($functionNames as $functionName){
if(method_exists($this, $functionName)){
continue;
}
$this->$functionName = function($params) use($variable){
echo $variable;
};
}
}
}
問題在於,通過這種方式創建函數,您實際上並不是在創建類方法,而是創建包含函數的類變量。
所以,你需要像這樣調用它:
$test = new Something;
$foo = $test->foo;
$foo('abc');
你不能只做$test->foo('abc');
。
編輯:你可以做的另一件事是使用PHP的__call
“魔術方法”。 無論方法是否存在,只要你執行->funcName()
,就會運行它。 使用該方法,您可以檢查調用的方法是'foo'
還是'bar'
。 看這個例子:
class Something{
private $variable;
public function __construct(){
$this->variable = 'blablabla';
}
public function __call($name, $params=array()){
if(method_exists($this, $name)){
// This makes sure methods that *do* exist continue to work
return call_user_func(array($this, $name), $params);
}
else{
$functionNames = array('foo', 'bar');
if(in_array($name, $functionNames)){
// You called ->foo() or ->bar(), so do something
// If you'd like you can call another method in the class
echo $this->variable;
}
}
}
}
有了這個,現在你可以做到以下幾點:
$test = new Something;
$test->foo('abc'); // Will echo "blablabla"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.