例如
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');