略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Closure::call

2024-12-22

Closure::call

(PHP 7, PHP 8)

Closure::call绑定并调用闭包

说明

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

暂时将闭包绑定到 newThis,并使用任意给定的参数调用它。

参数

newThis

在调用期间将闭包绑定到 object

args

零个或多个参数,他们将作为参数传递给闭包。

返回值

返回闭包的返回值。

范例

示例 #1 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);
?>

以上例程会输出:

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

User Contributed Notes 2 notes

up
3
sergey dot nevmerzhitsky at gmail dot com
5 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.
up
0
php-net at gander dot pl
10 months 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"

官方地址:https://www.php.net/manual/en/closure.call.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3