PHP 的 用 Closure::bind 绑定闭包

等级 4167 次按键

用 Closure::bind 把闭包绑定到 Vault 对象和 Vault 类作用域,使其能读取 private 属性;输出“Found: diamond”。

PHP 代码

1class Vault {
// private:通常无法在类外读取
2 private string $secret = "diamond";
3}
4
// Closure::bind 返回一个更换了 $this 和作用域的闭包副本
5$peek = Closure::bind(
6 function () {
// 绑定后,$this 就是 Vault 对象
7 return "Found: $this->secret";
8 },
// 第二个参数:成为 $this 的对象
9 new Vault(),
// 第三个参数:允许访问 private 成员的类作用域
10 Vault::class
11);
12
// 输出“Found: diamond”
13echo $peek();

运行结果

Found: diamond
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 PHP 代码中需要输入的符号及其出现次数。

  • :× 5
  • ;× 4
  • "× 4
  • (× 4
  • )× 4
  • $× 4
  • ,× 2
  • {× 2
  • }× 2
  • =× 2

PHP 等级 4 的更多代码示例

← 返回 PHP 打字练习