Unexpected T_PAAMAYIM_NEKUDOTAYIM in PHP 5.2.x

后端 未结 5 1354
情深已故
情深已故 2020-12-18 07:39

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...

相关标签:
5条回答
  • 2020-12-18 07:59

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 08:01

    I came here by the reference: Syntax error in PHP 5.2 where Chandresh mentioned your link: how ever one work around for PHP 5.2 is:

    class Sample{
        public static $name;
    
        public function __construct(){
            self::$name = "User 1";
        }
    }
    
    $sample = new Sample();
    $class = 'Sample';
    $name = 'name';
    $val_name = "";
    $str = '$class::$$name';
    eval("\$val_name = \"$str\";");
    //echo $val_name."<br>";
    eval("\$name = $val_name;");
    echo $name;
    

    Ignore if you already resolved. Thank you

    0 讨论(0)
  • 2020-12-18 08:02

    PHP Version 5.3.3, I am not getting any errors on that code.

    Output:

    string(0) "" string(3) "dev" string(4) "prod" string(0) ""

    Your error likely lies elsewhere. Please double check the reported line numbers.

    0 讨论(0)
  • 2020-12-18 08:05

    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

    0 讨论(0)
  • 2020-12-18 08:07

    Another case :

    It may happen on some servers (PHP VERSION ??) if you use: if (empty(NAME_OF_A_CONSTANT)) ...

    0 讨论(0)
提交回复
热议问题