Closure::call

(PHP 7, PHP 8)

Closure::callVincula e chama a closure

Descrição

public Closure::call ( object $newthis , mixed $... = ? ) : mixed

Vincula temporáriamente a closure ao newthis, e a chama com qualquer parâmetro fornecido.

Parâmetros

newthis

O objeto a ser vinculado a closure enquanto durar a chamada.

...

Zero ou mais parâmetros, que serão fornecidos como parâmetros para a closure.

Valor Retornado

Retorna o valor de retorna da closure.

Exemplos

Exemplo #1 Exemplo do método Closure::call()

<?php
class Value {
    protected 
$value;

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

    public function 
getValue() {
        return 
$this->value;
    }
}

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

$closure = function ($delta) { var_dump($this->getValue() + $delta); };
$closure->call($three4);
$closure->call($four4);
?>

O exemplo acima irá imprimir:

int(7)
int(8)
add a note add a note

User Contributed Notes 1 note

up
1
sergey dot nevmerzhitsky at gmail dot com
7 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