Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

php 5.2 - Unexpected T_PAAMAYIM_NEKUDOTAYIM in PHP 5.2.x

I'm having a hard time understanding why I'm getting an Unexpected T_PAAMAYIM_NEKUDOTAYIM error in the following code, which seems perfecly valid to me...

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;
}

Output in PHP 5.3+:

echo var_dump(instance()->getMyID()) . "
"; // null
echo var_dump(instance('dev')->getMyID()) . "
"; // dev
echo var_dump(instance('prod')->getMyID()) . "
"; // prod
echo var_dump(instance()->getMyID()) . "
"; // null

In prior versions however, I can't do $result::$id = strval($xpto);, does anyone know why?

Are there any workarounds for this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason for the error is simply that the syntax isn't supported in < 5.3.

However, if you're trying to just access the static variable $id, then the syntax would be:

$result::id

If you do need to access a static variable variable, then a workaround is to use reflection:

$class = new ReflectionClass($xpto);
echo $class->setStaticPropertyValue ('id', strval($xpto));

ReflectionClass


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...