Php: can’t assign a property value in declaration

Posted on

Php: can’t assign a property value in declaration – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about Php: can’t assign a property value in declaration.

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.

Solution :

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.

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.