php-类变量的作用域解析运算符

我很好奇为什么在类变量上使用范围解析运算符会导致致命的php错误,以及是否有解决方法.

例如:

<?php
class StaticTest
{
    public static function output()
    {
        echo "Output called<br />";
    }
}
Class Test
{
    public $reference;

    public function __construct()
    {
        $this -> reference = new StaticTest;
    }

}

$static_test = new StaticTest;
$static_test::output(); //works as intended

$test = new Test;
$test -> reference::output(); //Unexpcted T_PAAMAYIM_NEKUDOTAYIM

$direct_reference = $test -> reference;
$direct_reference::output(); //works, closest solution i have found, but requires the extra line of code / variable
?>

解决方法:

如果您唯一关心的是代码行数和额外变量,请按照以下步骤在一行中完成操作,而无需创建任何变量:

call_user_func(array(get_class($test->reference), 'output'));

我认为,这相当于:

$direct_reference = $test->reference;
$direct_reference::output();
上一篇:从父类PHP自动构造子类


下一篇:在初始化之外的Java中创建对象