PHP Closure类的bind()和bindTo()怎么用?
ringa_lee
ringa_lee 2017-04-11 10:42:14
0
2
308
ringa_lee
ringa_lee

ringa_lee

reply all (2)
Peter_Zhu

不知道你有没有用过js中的call或者apply, 有点类似.

其实就是把闭包当成对象的成员方法或者静态成员方法.

Closure::bind($cl1, null, 'A'); //就相当于在类里面加了个静态成员方法 Closure::bind($cl2, new A(), 'A'); //相当于在类里面加了个成员方法

成员方法中使用$this访问对象, 静态成员方法直接使用类名::成员的方法.
但是因为是匿名函数, 没有函数名, 所以返回一个已经绑定$this对象和类作用域的闭包给你使用.

    巴扎黑
    ifoo; //无权限 echo "\n#2\n"; $callable1 = Closure::bind(function () { return $this::$sfoo; }, $aObj, 'A'); echo $callable1(); //1 echo "\n#3\n"; $callable2 = Closure::bind(function () { return $this->ifoo; }, $aObj, 'A'); echo $callable2(); //2 echo "\n#4\n"; $callable3 = Closure::bind(function () { return A::$sfoo; //phpStorm 会报红 }, null, 'A'); echo $callable3(); //1
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!