PHP 5.2.x中出现意外的T_PAAMAYIM_NEKUDOTAYIM

Ali*_*xel 5 php php-5.2

我很难理解为什么我Unexpected T_PAAMAYIM_NEKUDOTAYIM在下面的代码中出现错误,这对我来说似乎完全有效......

class xpto
{
    public static $id = null;

    public function __construct()
    {
    }

    public static function getMyID()
    {
        return self::$id;
    }
}

function instance($xpto = null)
{
    static $result = null;

    if (is_null($result) === true)
    {
        $result = new xpto();
    }

    if (is_object($result) === true)
    {
        $result::$id = strval($xpto);
    }

    return $result;
}
Run Code Online (Sandbox Code Playgroud)

PHP 5.3+中的输出:

echo var_dump(instance()->getMyID()) . "\n"; // null
echo var_dump(instance('dev')->getMyID()) . "\n"; // dev
echo var_dump(instance('prod')->getMyID()) . "\n"; // prod
echo var_dump(instance()->getMyID()) . "\n"; // null
Run Code Online (Sandbox Code Playgroud)

然而,在以前的版本中,我做不到$result::$id = strval($xpto);,有谁知道为什么?

这个问题有没有解决方法?

Chr*_*ker 1

查看键盘后:

if (is_object($result) === true)
{
    $result::id = strval($xpto);
}
Run Code Online (Sandbox Code Playgroud)

... 应该

if (is_object($result) === true)
{
    $result::$id = strval($xpto);
}
Run Code Online (Sandbox Code Playgroud)

我在新的粘贴中纠正了这个问题,但错误仍然存​​在......只是让您了解演示代码中的问题。

编辑

根据static关键字的 PHP 文档页面,

从 PHP 5.3.0 开始,可以使用变量引用该类。变量的值不能是关键字(例如 self、parent 和 static)。

不幸的是,没有详细说明为什么在之前的版本中是这样,我也没有看到评论中提出的解决方法。

不过,由于该类是静态的,因此您应该能够直接更改该属性:

function instance($xpto = null)
{
    static $result = null;

    if (is_null($result) === true)
    {
        $result = new xpto();
    }

    if (is_object($result) === true)
    {
        xpto::$id = strval($xpto)
    }

    return $result;
}
Run Code Online (Sandbox Code Playgroud)