php - 为什么在使用静态作用域时闭包与闭包类相关联?
问题描述
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 具有相同的范围。
我试图检查源代码,但没有发现哪里出了问题。
解决方案
因为根据https://www.php.net/manual/en/closure.bindto.php,将第二个参数 ($newScope) 设置为 'static' 会保留当前的Closure
. 设置第一个参数 ($newThis) 只会影响 的值$this
。要将 的值绑定self::
到 $newThis 的类,请执行以下操作:
$newclosure = $closure->bindTo($newThis, $newThis);
推荐阅读
- python - 在方法中获取类属性
- python - 反转 LinkedList 的嵌套输出
- java - Java中是否有JSON库可以轻松替换JSON树中的值,我只知道值但不知道映射到它的字段/键?
- php - 在 MySQL 表上插入一个 php 字符串作为多行
- php - Jquery Load 函数需要大量时间来刷新或加载数据。我怎样才能让它更快
- python - 切片和性能
- c# - 如何在 C# 中使用从 ClientWebSocket 接收的数据?
- java - 如何在数据集中搜索值
在java火花?
- javascript - 如何获取 fs.createWriteStream 并将其上传到 Gapi google drive api create 函数?
- arrays - MIPS 交换两个数组元素