class attribute declaration [closed]

孤人 提交于 2020-01-05 12:58:21

问题


I didn't use PHP in a while, but I've tried something like this:

<?php

class Something {
    public $x = 2 * 3;   // (line 4)
}

This code triggers the following error:

[Wed Feb 13 17:43:56 2013] [error] [client 127.0.0.1] PHP Parse error: syntax error, unexpected '*', expecting ',' or ';' in /var/www/problem.php on line 4

The PHP documentation says

this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

So, according to the docs, my code should work. Is there something I'm missing here?


回答1:


When declaring members of a class you can assign values to them but you can't do complex operations like math or function calls.

<?php

class Something {
    public $x = 2 * 3;   // (line 4)
}

can be:

<?php

class Something {
    public $x = 6;   // (line 4)
}

So in your case you'll want to initialize that value in your constructor instead.

<?php

class Something {
    public $x; 

    public function __construct() 
    {
        $this->x = 2 * 3;
    }  
}



回答2:


If you actually read carefully the documentation you linked to in the examples it clearly says that this is not allowed:

class SimpleClass
{
    // invalid property declarations:
    // (some examples here)
    public $var3 = 1+2;
}

This implies that multiplication won't work either.




回答3:


So, according to the docs, my code should work.

nope

The docs clearly state: "it must be able to be evaluated at compile time and must not depend on run-time information"

2 * 3 is run-time evaluation.

public $x = 6; should work.




回答4:


Run-time evaluation 2 * 3 is not allowed.

As the DOCS say

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.



来源:https://stackoverflow.com/questions/14857422/class-attribute-declaration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!