PHP Closure类Bind与BindTo方法

Closure类为闭包类,PHP中闭包都是Closure的实例:php

1     $func = function(){};
2     var_dump($func instanceof Closure);

输出   bool(true)

Closure有两个函数将闭包函数绑定到对象上去,laravel

静态方法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。this

class Father 
{
    public $pu = "public variable";

    public static $spu = 'public static';
}

class Son extends Father
{

}

class Other 
{

}

$son = new Son();
$func = function(){
    echo self::$spu;
};

($func -> bindTo(null, 'Son'))();

静态闭包中不能够调用$this,不然会报错。就像类的静态方法不能够调用$this同样spa

    $son = new Son();
    $func = function(){
        echo $this -> $pu;
    };

    ($func -> bindTo(null, 'Son'))();
报错:
Fatal error: Uncaught Error: Using $this when not in object context in D:\laravel\test.php:21
Stack trace:

类做用域:.net

当闭包绑定到对象上时,或者绑定到null成为静态对象,能够经过返回的闭包对象来调用对象的方法,同时能够设定第三个参数$newscope来设定对象中 code

属性或方法对于闭包的访问可见性。闭包的访问可见性和$newscope类的成员函数是相同的。对象

    class Father 
    {
        protected $pu = "public variable";

        protected static $spu = 'public static';
    }

    class Son extends Father
    {

    }
        //Son中的方法能够正常访问Father类中的protected属性

    class Other 
    {

    }
        //Other中的方法没法访问Father类中的protected属性


测试:

    $son = new Son();

    $func = function(){
        echo $this -> pu;
    };

    (Closure::bind($func, $son, 'Son'))();
    输出 public variable
    (Closure::bind($func, $son, 'Other'))();
    报错 Fatal error: Uncaught Error: Cannot access protected property Son::$pu

  

匿名函数都是Closure的实例因此能够调用 bindTo 方法。
bindTo方法
($func -> bindTo($son, 'Son'))();
($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

相关文章
相关标签/搜索