首页 > 解决方案 > 为什么在使用静态作用域时闭包与闭包类相关联?

问题描述

class someScope {
}

$newThis = new someScope;

$closure = function () {
    self::__invoke(); // to check the scope
};

// This is expected behaviour:
$closure(); // Error: Cannot access self:: when no class scope is active. 

$newclosure = $closure->bindTo($newThis, "static");

// Unexpected behaviour:
$newclosure(); // Error: Call to undefined method Closure::__invoke()

如您所见,由于某种原因,$newclosure 与 Closure 类相关联。我预计与以前相同的错误,因为据我了解“静态”范围意味着 $newclosure 与 $closure 具有相同的范围。

我试图检查源代码,但没有发现哪里出了问题。

标签: php

解决方案


因为根据https://www.php.net/manual/en/closure.bindto.php,将第二个参数 ($newScope) 设置为 'static' 会保留当前的Closure​​. 设置第一个参数 ($newThis) 只会影响 的值$this。要将 的值绑定self::到 $newThis 的类,请执行以下操作:

$newclosure = $closure->bindTo($newThis, $newThis);

推荐阅读