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 中一样。如何才能实现这一目标?
这个怎么样:
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
});
这里
$this
作为可调用函数的参数提供。