Closure::call

(PHP 7, PHP 8)

Closure::callVincula y llama al cierre

Descripción

public Closure::call(object $newThis, mixed ...$args): mixed

Vincula temporalmente el cierre a newThis, y lo llama con cualquier parámetro dado.

Parámetros

newThis

El object a vincular al cierre mientras dure la llamada.

args

Cero o más parámetros, que serán dados como parámetros al cierre.

Valores devueltos

Devuelve el valor devuelto por el cierre.

Ejemplos

Ejemplo #1 Ejemplo de Closure::call()

<?php
class Valor {
protected
$valor;

public function
__construct($valor) {
$this->valor = $valor;
}

public function
getValor() {
return
$this->valor;
}
}

$tres = new Valor(3);
$cuatro = new Valor(4);

$cierre = function ($delta) { var_dump($this->getValor() + $delta); };
$cierre->call($tres, 4);
$cierre->call($cuatro, 4);
?>

El resultado del ejemplo sería:

int(7)
int(8)
add a note

User Contributed Notes 2 notes

up
4
php-net at gander dot pl
3 years ago
You can also access private data:<?phpclass Value {    private $value;    public function __construct($value) {        $this->value = $value;    }}$foo = new Value('Foo');$bar = new Value('Bar');$closure = function () { var_dump($this->value); };$closure->call($foo);$closure->call($bar);?>Output:string(3) "Foo"string(3) "Bar"
up
4
sergey dot nevmerzhitsky at gmail dot com
8 years ago
Prior PHP 7.0 you can use this code:<?php$cl = function($add) { return $this->a + $add; };$cl->bindTo($newthis);return call_user_func_array($cl, [10]);?>But this bind the closure permanently! Also read the article for Closure::bindTo() about binding closures from static context.
To Top