gpt4 book ai didi

php - 是否可以在不使用全局变量的情况下模拟 PHP 5.2.x 中的闭包?

转载 作者:可可西里 更新时间:2023-10-31 23:09:41 25 4
gpt4 key购买 nike

是否可以在不使用全局变量的情况下在 PHP 5.2.x 中模拟闭包?我可以想出一种方法,将所需变量作为额外参数传递给闭包,但这并不是最佳实践。

有什么想法吗?

最佳答案

有趣的问题。我会说根本不可能,但让我们看看

引用 IBM - What's new in PHP5.3, Part 2

A closure is a function that is evaluated in its own environment, which has one or more bound variables that can be accessed when the function is called.

进一步(强调我的)

Variables to be imported from the outside environment are specified in the use clause of the closure function definition. By default, they are passed by value, meaning that if we would update the value passed within the closure function definition, it would not update the outside value.

使用 global 将通过引用传递,尽管可以通过在 use 子句中使用 & 将变量通过引用与闭包绑定(bind), 它已经偏离了 5.3 的默认行为。

$var = 'yes';
$fn = create_function('', 'global $var; $var = "no";');
$fn();
echo $var; // outputs no

您可以复制全局变量以便按值使用它,例如

$var = 'yes';
$fn = create_function('', 'global $var; $tmp = $var; $tmp = "no";');
$fn();
echo $var; // outputs yes

此外,全局变量的值(使用create_function时)不会在创建函数时计算(绑定(bind)),而是在函数运行时计算(绑定(bind))

$var = 'yes';
$fn = create_function('', 'global $var; $tmp = $var; return $tmp;');
$var = 'maybe';
echo $fn(); // outputs maybe

$var = 'yes';
$fn = function() use ($var) { return $var; };
$var = 'maybe';
echo $fn(); // outputs yes

同样重要的是

When defined within an object, one handy thing is that the closure has full access to the object through the $this variable, without the need to import it explicitly. *Though I think this was dropped in final PHP5.3

这对于 global 关键字是不可能的,您也不能只使用 $this。使用 create_function 定义函数体时,无法从类中引用属性。

class A {

protected $prop = 'it works';

public function test()
{
$fn = create_function('', 'echo $this->prop;');
return $fn;
}
}

$a = new A;
$fn = $a->test();
$fn();

会导致

Fatal error: Using $this when not in object context

总结一下
虽然您可以创建一个从全局范围导入变量的函数,但您不能使用来自另一个范围的变量来创建一个函数。因为从技术上讲,您在使用 create_function 时没有绑定(bind),而是在执行创建的函数时导入,所以我想争辩说这种限制使闭包成为 lambda


编辑:下面由 Onno Marsman 提供的解决方案非常不错。它没有完全模拟闭包,但实现非常接近。

关于php - 是否可以在不使用全局变量的情况下模拟 PHP 5.2.x 中的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2209327/

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