gpt4 book ai didi

PHP:将函数分配给类方法

转载 作者:搜寻专家 更新时间:2023-10-31 20:39:06 25 4
gpt4 key购买 nike

如何在 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"

关于PHP:将函数分配给类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27661292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com