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
186 views
in Technique[技术] by (71.8m points)

Initializing PHP class property declarations with simple expressions yields syntax error

According to the PHP docs, one can initialize properties in classes with the following restriction:

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

I'm trying to initialize an array and having some issues. While this works fine:

public $var = array(
    1 => 4,
    2 => 5,
);

This creates a syntax error:

public $var = array(
    1 => 4,
    2 => (4+1),
);

Even this isn't accepted:

public $var = 4+1;

which suggests it's not a limitation of the array() language construct.

Now, the last time I checked, "4+1" equated to a constant value that not only should be accepted, but should in fact be optimized away. In any case, it's certainly able to be evaluated at compile-time.

So what's going on here? Is the limitation really along the lines of "cannot be any calculated expression at all", versus any expression "able to be evaluated at compile time"? The use of "evaluated" in the doc's language suggests that simple calculations are permitted, but alas....

If this is a bug in PHP, does anyone have a bug ID? I tried to find one but didn't have any luck.

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

PHP doesn't do such operations at compile-time; you cannot assign calculated values to constants, even if all operators are constants themselves. Default values of class members are treated the exact same way. I encountered this behaviour as I tried to assign powers of two to constants:

class User {
    const IS_ADMIN = 1;
    const IS_MODERATOR1 = 1 << 1; // Won't work
    const IS_MODERATOR2 = 0x02;   // works
}

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

...