gpt4 book ai didi

php - Closure::bindTo 是如何工作的?

转载 作者:可可西里 更新时间:2023-11-01 13:17:20 26 4
gpt4 key购买 nike

例如,我有一些代码:

class A
{
private $value = 100;
}
$a = new A;
$closure = function(){echo $this->value;};
$binding = $closure->bindTo($a,"A"); /// tag
$binding();

我有一些问题:

  1. 当我们在标记为 tag 的行中将第二个参数写为“A”时,是否意味着匿名函数内部的执行上下文与类“A”内部的执行上下文相同?
  2. 如果在将要执行的匿名函数的上下文中而不是“A”写入“static”?
  3. 如果我们在第二个参数中写入“static”,那么它是否与 LSB 相关?

最佳答案

让我来帮助您解读手册 http://php.net/Closure.bindTo

newscope

The class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.

所以,要回答你的第一个问题,是的,这意味着代码被解释为 A 类的方法。

如果上下文是"static"(第二个问题),那么在执行时你会得到:

Fatal error: Cannot access private property A::$value in php shell code on line 1

那是因为 "static"保持当前的[范围](即闭包设置为持续的范围;例如,如果它绑定(bind)到 A,它将保持绑定(bind)到 A)。在这种情况下,它只是没有作用域,现在仍然没有作用域;它并没有神奇地表现得像它是 A 类(或任何扩展它的类)的一部分,因此无法访问 protected 或私有(private)属性。

关于第三个问题,这里的“static”只是保留当前设置的作用域。它没有进一步的意义。 "static" 作为标识符的唯一原因是任何类都不能命名为 static(因此它不会与任何可能的类名冲突)。

即(使用初始示例中的 $closure):

$binding = $closure->bindTo($a, "A"); // scope is now A class
$second_binding = $binding->bindTo($a, "static"); // scope is still A class
$second_binding(); // works fine, no access issues

关于php - Closure::bindTo 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39884308/

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