Reputation: 17721
I do not understand the rationale behind the different treatment of variable assignment between global context and class context:
$var1 = "a" . "b"; # PHP syntax o.k.
class myClass {
private $var2 = "a" . "b"; # PHP Parse error: syntax error, unexpected '.', expecting ',' or ';'
}
P.S.: visibility of property (private/protected/public) doesn't play a role.
Upvotes: 2
Views: 1258
Reputation: 522382
It's not a "variable assignment in class context". private $var
declares a property for the class, and you're additionally giving it a default value. You're declaring the structure of the class here, which is not the same as a variable assignment in procedural code. The class structure is parsed by the parser and compiled by the compiler and the default value for the property is established in this parsing/compilation step. The compiler does not execute any procedural code; it can only handle constant values.
As such, you cannot declare class properties with default values which need evaluation, because the part of PHP that handles the declaration of classes, the parser/compiler, does not evaluate.
Upvotes: 5
Reputation: 212452
Quoting from the PHP docs (my emphasis)
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.
Instead, define values in the constructor if they're dependent on any evaluation.
Upvotes: 3