欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP7之Closure::call javascript closure need for closure google closur

程序员文章站 2022-05-19 19:58:40
...

Closure 类:匿名函数(在 PHP 5.3 中被引入)会产生这个类型的对象。
可将该类绑定到类或者对象上,即将自定义的方法动态添加到类或者对象上

php7之前使用的方法

  • Closure::bind :复制一个闭包,绑定指定的$this对象和类作用域。这个方法是 Closure::bindTo() 的静态版本

  • Closure::bindTo :复制当前闭包对象,绑定指定的$this对象和类作用域。创建并返回一个 匿名函数, 它与当前对象的函数体相同、绑定了同样变量,但可以绑定不同的对象,也可以绑定新的类作用域。

php7添加

  • Closure::call() : 方法被添加作为临时绑定的对象范围,以封闭并简便调用它的方法。它的性能相比PHP5.6 bindTo要快得多。
//bind.php/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 22:35
 */classA {privatestatic$sta = 1;
    private$com = 2;
}
$cl1 = staticfunction() {return A::$sta;
};
$cl2 = function() {return$this->com;
};

$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo$bcl1(), "\n";
echo$bcl2(), "\n";
//bindTo.php/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 22:35
 */classA {function__construct($val) {$this->val = $val;
    }
    functiongetClosure() {//returns closure bound to this object and scopereturnfunction() {return$this->val; };
    }
}

$ob1 = new A(1);
$ob2 = new A(2);

$cl = $ob1->getClosure();
echo$cl(), "\n";

$add = function(){return$this->val+1;
};
$cl = $add->bindTo($ob2);
//与call相比,需要增加()方可被调用echo$cl(), "\n";
//call.php/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 22:35
 */classValue {protected$value;

    publicfunction__construct($value) {$this->value = $value;
    }

    publicfunctiongetValue() {return$this->value;
    }
}

$three = new Value(3);
$four = new Value(4);

$closure = function($delta) {return$this->getValue() + $delta; };
//可直接调用,不用在后面增加()echo$closure->call($three, 3);
echo$closure->call($four, 4);
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了PHP7之Closure::call,包括了closure,php7方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

相关标签: closure php7