Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected T_PAAMAYIM_NEKUDOTAYIM in PHP 5.2.x

Tags:

php

php-5.2

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()) . "\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

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

Are there any workarounds for this problem?

like image 503
Alix Axel Avatar asked Feb 14 '11 17:02

Alix Axel


2 Answers

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

like image 159
webbiedave Avatar answered Nov 16 '22 22:11

webbiedave


After looking at codepad:

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

... should be

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

I corrected this in a new paste, and the error still exists... just letting you know about the problem in the demo code.

EDIT

Per PHP documentation page on static keyword,

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Unfortunately, no detail is given as to WHY to was otherwise in prior versions, nor do I see a workaround presented in the comments.

Because the class is static, though, you should be able to change the property directly:

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;
}
like image 20
Chris Baker Avatar answered Nov 17 '22 00:11

Chris Baker