【发布时间】:2015-02-24 00:16:37
【问题描述】:
如何在 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
有谁知道我如何将匿名函数分配给类方法,同时仍然能够访问该函数之外的变量?
【问题讨论】:
-
我认为在 PHP 中这是不可能的。我认为您必须实例化一个对象或让一个函数返回一些将某些东西分配给变量的东西。不过,这不是一个坏问题。
-
你不能在类构造函数中返回。它会抛出一个错误。 php.net/manual/en/language.oop5.decon.php
-
@versalle88 是的,这是真的......我实际上有一个 foreach 循环,
return;是一个continue;,但我决定稍微简化一下代码,因为(我认为)它是没必要。不过我会编辑它 -
虽然还是不行,但是在赋值匿名函数的时候,不要在变量上使用大括号:
$this->{$functionName[0]} = function($params){ -
我不明白这是如何工作的。构造函数返回后,$variable 的值将存储在哪里?