PHP 8.4.0 RC4 available for testing

Closure::call

(PHP 7, PHP 8)

Closure::callLie et appelle la fermeture

Description

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

Lie temporairement la fermeture (closure) à newThis, et l'appelle avec les paramètres donné.

Liste de paramètres

newThis

L'objet auquel lier la fermeture pour la durée de l'appel.

args

Zéro ou plusieurs paramètres, qui seront donnés en tant que paramètres à la fermeture.

Valeurs de retour

Retourne la valeur de retour de la fermeture.

Exemples

Exemple #1 Exemple deClosure::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($three, 4);
$closure->call($four, 4);
?>

L'exemple ci-dessus va afficher :

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:

<?php
class 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