牛牛在线工具

Closure::call()

收录 8868 个 PHP 函数,含用途说明与用法示例。

Closure::call()

调用闭包函数,并传递指定的 $this 对象和参数列表

函数名称:Closure::call() 适用版本:5.4.0及以上版本 函数用法: Closure::call() 函数用于调用闭包函数,并传递指定的 $this 对象和参数列表。它允许你在闭包函数中,使用不同的 $this 对象来调用。 语法: Closure::call($closure, $newThis, ...$parameters) 参数说明: $closure:要调用的闭包函数。 $newThis:要绑定到闭包函数中的 $this 对象。 $parameters:要传递给闭包函数的参数列表。 返回值: 该函数返回闭包函数的结果。 示例: 假设有一个包含私有属性的类 Person,我们想在不改变私有属性的情况下,调用私有方法 display()。可以使用 Closure::call() 来实现: class Person { private $name; private function display() { echo 'My name is ' . $this->name; } } $person = new Person(); $person->name = 'John'; $closure = function() { $this->display(); }; Closure::call($closure, $person); 上述示例中,我们定义了一个闭包 $closure,然后使用 Closure::call() 来调用它,并传递 $person 对象作为 $this 参数。闭包中的 $this 对象被绑定到 $person 对象,因此可以成功调用私有方法 display(),输出结果为 "My name is John"。 需要注意的是,$this 对象必须是一个对象实例,而不能是类名或 null。