标签:
Closure类为闭包类,PHP中闭包都是Closure的实例:
1 $func = function(){}; 2 var_dump($func instanceof Closure);
输出 bool(true)
Closure有两个函数将闭包函数绑定到对象上去,
静态方法Bind
public static Closure Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = ‘static‘ ] )
动态方法BindTo
public Closure Closure::bindTo ( object $newthis [, mixed $newscope = ‘static‘ ] )
静态闭包不能有绑定的对象($newthis
参数的值应该设为 NULL )
此时Closure不可以使用$this。
1 class Father 2 { 3 public $pu = "public variable"; 4 5 public static $spu = ‘public static‘; 6 } 7 8 class Son extends Father 9 { 10 11 } 12 13 class Other 14 { 15 16 } 17 18 $son = new Son(); 19 $func = function(){ 20 echo self::$spu; 21 }; 22 23 ($func -> bindTo(null, ‘Son‘))();
静态闭包中不可以调用$this,否则会保持。就像类的静态方法不可以调用$this一样
1 $son = new Son(); 2 $func = function(){ 3 echo $this -> $pu; 4 }; 5 6 ($func -> bindTo(null, ‘Son‘))(); 7 报错: 8 Fatal error: Uncaught Error: Using $this when not in object context in D:\laravel\test.php:21 9 Stack trace:
类作用域:
当闭包绑定到对象上时,或者绑定到null成为静态对象,可以通过返回的闭包对象来调用对象的方法,同时可以设定第三个参数$newscope来设定对象中
属性或方法对于闭包的访问可见性。闭包的访问可见性和$newscope类的成员函数是相同的。
1 class Father 2 { 3 protected $pu = "public variable"; 4 5 protected static $spu = ‘public static‘; 6 } 7 8 class Son extends Father 9 { 10 11 } 12 //Son中的方法可以正常访问Father类中的protected属性 13 14 class Other 15 { 16 17 } 18 //Other中的方法无法访问Father类中的protected属性
测试:
1 $son = new Son(); 2 3 $func = function(){ 4 echo $this -> pu; 5 }; 6 7 (Closure::bind($func, $son, ‘Son‘))(); 8 输出 public variable
9 (Closure::bind($func, $son, ‘Other‘))(); 10 报错 Fatal error: Uncaught Error: Cannot access protected property Son::$pu
匿名函数都是Closure的实例所以可以调用 bindTo 方法。
1 bindTo方法 2 ($func -> bindTo($son, ‘Son‘))(); 3 ($func -> bindTo($son, ‘Other‘))();
$newscope默认为‘Static‘表示不改变,还是之前的作用域。
class Grand { protected $Grandvar = ‘this is grand‘; } class Father extends Grand { protected $Fathervar = "this is Father"; } class Mother extends Grand { protected $Mothervar = ‘this is Mother‘; } class Son extends Father { protected $Sonvar = ‘this is son‘; } $son = new Son(); $mon = new Mother(); $func = function(){ echo $this -> Grandvar; }; 绑定访问作用域为‘Son‘的作用域,之后使用之前的默认作用域, 所以可以访问Grandvar $newFunc = Closure::bind($func, $son, ‘Son‘); $newFunc = Closure::bind($newFunc, $mon); $newFunc(); 未绑定访问作用域,默认没有权限 $newFunc = Closure::bind($func, $mon); $newFunc();
http://php.net/manual/zh/class.closure.php
标签:
原文地址:http://www.cnblogs.com/yangxunwu1992/p/5527855.html