标签:
从手册知道,Closure::bindTo — 复制当前闭包对象,绑定指定的$this对象和类作用域。
创建并返回一个 匿名函数, 它与当前对象的函数体相同、绑定了同样变量,但可以绑定不同的对象,也可以绑定新的类作用域。
从我个人理解,和js里面的call函数有点类似。可以改变闭包对象指定的作用域。
示例1:
<?php class A { function __construct($val) { $this->val = $val; } function getClosure() { return function(){return $this->val;}; } } $ob1 = new A(1); $cl = $ob1->getClosure(); echo $cl(),"<br/>"; $ob2 = new A(2); $cl = $cl->bindTo($ob2); //闭包指定作用域在$ob2对象上。 echo $cl()."<br/>"; //2
示例2:
<?php header("Content-type:text/html;charset=utf-8"); class Yifang { public $title = ‘武汉亿房网‘; public $tpl = ‘tpl1.php‘; } class Bentian { public $title = ‘东风本田‘; public $tpl = ‘tpl2.php‘; } class views { public function render($obj) { $name = $obj->tpl; $closure = function() use($name){ include ‘./tpl/‘.$name; }; $closure = $closure->bindTo($obj); return $closure; } } $View = new views(); call_user_func($View->render(new Bentian())); call_user_func($View->render(new Yifang()));
分别对应的2个模板
1 <?php 2 //tpl1 3 4 echo ‘======================<br/>‘; 5 echo $this->title."<br/>"; 6 echo ‘武汉江汉区<br/>‘; 7 echo ‘===========================‘; 8 9 ?> 10 11 <?php 12 //tpl2 13 14 echo ‘===========================<br/>‘; 15 echo $this->title."<br/>"; 16 echo ‘屯口经济开发区<br/>‘; 17 echo ‘===========================‘; 18 19 ?>
标签:
原文地址:http://www.cnblogs.com/loveyouyou616/p/5666740.html