返回对方法的引用?

时间:2014-01-30 03:14:09

标签: php oop reference static-methods

示例:

Class Test {
    private function __construct() {}

    public static function init() {
        $new_test = new Test();
        return $new_test->inner_test;
    }

    public function inner_test() {
        print '!!!!';
    }
}

$test = Test::init();
$test();

返回“PHP致命错误:函数名称必须是字符串”

有没有办法在PHP中完成这种Javascript类型行为?

2 个答案:

答案 0 :(得分:0)

PHP 5.4以下

Class Test {
    private function __construct() {}

    public static function init() {
        $new_test = new Test();
        return $new_test->inner_test();
    }

    public function inner_test() {
        print '!!!!';
    }
}

$test = array('Test','init');
call_user_func($test);

菲尔:

function test(){
echo "Hello";
}
$test = test;
$test();

在沙盒中运行它。

答案 1 :(得分:0)

感谢Phil的链接。这有效:

Class Test {
    private function __construct($myString) {
        $this->myString = $myString;
    }

    public static function init($myString) {
        $new_test = new Test($myString);
        return function() use (&$new_test) {$new_test->inner_test();};
    }

    public function inner_test() {
        print $this->myString;
    }
}

$test = Test::init('Lorem Ipsum Dolar');
$test();