【问题标题】:Return a reference to a method?返回对方法的引用?
【发布时间】:2014-01-30 03:14:08
【问题描述】:

例子:

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 类型的行为?

【问题讨论】:

  • PHP 不能像 JS 那样返回函数引用。也许尝试阅读php.net/manual/functions.anonymous.php
  • @Phil,是的,它可以...您只需将变量分配给指针。他很接近,但因为他分配了一个类,所以他必须使用一个数组。
  • @Thomas 不,它不能
  • 您需要一个自定义的可调用包装器,或者将其包装在一个匿名函数中,否则返回一个 [$this, 'methodname'] 对,但使用 call_user_func 调用它。
  • 我知道 call_user_func 经常被使用,我发布的例子工作得很好。

标签: php oop reference static-methods


【解决方案1】:

低于 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();

在沙箱中运行它。

【讨论】:

  • 现在我看了一下,这只适用于较新的 PHP 版本,这是我主要使用的。
  • $test() 语法对我来说是一个新语法。虽然找不到对它的记录参考
  • 你的小例子给了我 PHP 注意:使用未定义的常量测试 - 假定为“测试”。那只是 PHP 字符串扩展。你用$test = ['Test', 'init']; $test() 的例子更酷
  • 是的,现在我明白了你真正想要的原理,这将无济于事(尽管它在大多数框架中用于回调)。我现在看到您想将 inner_test 作为值返回并将其用作回调。今天对我来说太久了。
【解决方案2】:

感谢菲尔提供链接。这有效:

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();

【讨论】:

  • 请注意,匿名函数直到 PHP 5.3 才存在
  • 是的。由于这个限制,我实际上不会使用它,但这正是我想要的。
  • 检查我的答案,我对其进行了编辑,因此它可以在大多数情况下与任何 PHP 一起使用。
猜你喜欢
  • 1970-01-01
  • 2018-05-28
  • 2021-01-30
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 2019-03-14
  • 1970-01-01
相关资源
最近更新 更多