views:

100

answers:

2

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.

+1  A: 

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
}
soulmerge
That last one is a hex value, not an operation.
SeanJA
I know, just wanted to show that I had to fall back to a constant instead of the bit shift.
soulmerge
Okay, well at least I know I'm not crazy. Although it'd be nice if very simple expressions were supported, I don't really mind either way so long as the docs are clear. And that, they're not. I'll file a bug when I get a chance.Thanks!
+2  A: 

Before you throw your arms up at php for this, think about the execution model. In the environment that php is typically used for(and, in fact, designed for), everything is built up, executed, and then thrown away...until the next http request comes in. It doesn't make a lot of sense to waste time doing computations during the parsing/compilation phase. The engine needs to be very swift here in the general case.

But, you're right, that quote from the manual does say "evaluate". Maybe you should open a documentation ticket.

chris