this 在可调用的上下文中?

问题描述 投票:0回答:1
class foo {
    function bar(callable $callable) {
        $callable();
    }

    function printStr() {
        echo "hi";
    }
}

$foo = new foo();
$foo->bar(function () {
    $this->printStr(); // Using $this when not in object context
});

是的,您需要传递一个匿名函数来调用 foo 类的方法。正如在 JS 中一样。如何才能实现这一目标?

php callable
1个回答
0
投票

这个怎么样:

class foo {
    function bar(callable $callable) {
        $callable($this);
    }

    function printStr() {
        echo "hi";
    }
}

$foo = new foo();
$foo->bar(function ($that) {
    $that->printStr(); // Using $this when not in object context
});

演示:https://3v4l.org/VbnNH

这里

$this
作为可调用函数的参数提供。

© www.soinside.com 2019 - 2024. All rights reserved.