【问题标题】:PHP: Get static method referencePHP:获取静态方法参考
【发布时间】:2015-08-30 20:04:54
【问题描述】:

我想从同一个类中的另一个静态方法中获取一个静态方法的引用,但是 PHP 总是将这两行(参见下面的示例代码)解释为对常量的访问。 PHP中不能获取静态方法的引用吗?

class foo
{
    public static function test()
    {
        self::bar();  // calling (not referencing) works
        $bar_reference = self::bar;  // Error: Undefined class constant 'bar'
    }

    public static function bar()
    {
        echo "hello";
    }
}

foo::test();
$bar_reference = foo::bar;  // Error: Undefined class constant

再次澄清一下:我不想调用静态方法 - 我只想获得对它的引用。

【问题讨论】:

  • PHP 没有对标识符的引用。您只能引用变量。或者对回调使用字符串化标识符。
  • @mario:出于所有意图和目的,字符串化标识符确实是 PHP 中的引用,
  • 如果不可能,那好吧。但我不明白为什么这是对我的问题投反对票的理由(或者我问错了什么?)

标签: php class reference static


【解决方案1】:

您可以像这样创建callable

class foo 
{
    public static function test()
    {   
        $bar_reference = array(__CLASS__, 'bar');
        // Call it
        $bar_reference();
    }   

    public static function bar()
    {   
        echo "hello";
    }   
}

foo::test();
$bar_reference = foo::bar();

【讨论】:

  • 好的。你想用这个参考做什么?
猜你喜欢
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多