class attribute declaration [closed]

2019-07-29 08:59发布

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?

标签: php class object
4条回答
我只想做你的唯一
2楼-- · 2019-07-29 09:34

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楼-- · 2019-07-29 09:36

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.

查看更多
Ridiculous、
4楼-- · 2019-07-29 09:51

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.

查看更多
SAY GOODBYE
5楼-- · 2019-07-29 09:54

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;
    }  
}
查看更多
登录 后发表回答