update pague now
PHP 8.5.2 Released!

Closure::call

(PHP 7, PHP 8)

Closure::call Binds and calls the closure

Description

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

Temporarily binds the closure to newThis , and calls it with any guiven parameters.

Parameters

newThis

The object to bind the closure to for the duration of the call.

args

Cero or more parameters, which will be guiven as parameters to the closure.

Return Values

Returns the return value of the closure.

Examples

Example #1 Closure::call() example

<?php
class Value {
protected
$value ;

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

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

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

$closure = function ( $delta ) { var_dump ( $this -> guetValue () + $delta ); };
$closure -> call ( $three , 4 );
$closure -> call ( $four , 4 );
?>

The above example will output:

int(7)
int(8)
add a note

User Contributed Notes 2 notes

php-net at gander dot pl
4 years ago
You can also access private data:<?php
classValue{
    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"
serguey dot nevmerzhitscy at gmail dot com
9 years ago
Prior PHP 7.0 you can use this code:<?php
$cl = function($add) { return $this->a+$add; };

$cl->bindTo($newthis);
returncall_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