如何在PHP中将成员方法转换为函数指针


How to turn member method into a function pointer in PHP?

例如

class Foo {
    public function testFn($fn) {
        $fn();
    }
    public function hello() {
        echo 'World';
    }
}

那么,如何将hello方法传递到testFn方法中呢?(通过我的意思是通过任何类中的任何成员方法)

例如

 $bar = new Foo();
 $bar->testFn($bar->hello); // this will not work 
<?php
class Foo {
    public function testFn($fn) {
        $this->$fn();
    }
    public function hello() {
        echo 'World';
    }
}
$bar = new Foo();
$bar->testFn('hello');
$bar = new Foo();
$bar->testFn([$bar, 'hello']);

请参阅有关callable伪类型的文档。

哦,这是一个奇怪的代码。。。但它有效:

class Foo {
    public function testFn($fn) {
        $this->$fn();
    }
    public function hello() {
        echo 'World';
    }
}
$bar = new Foo();
$bar->testFn('hello');