(4 1)"? " /> (4 1)"? " />
Question:
Despite PHP documentation stating that property initialization can include constant values, attempting to initialize an array using simple expressions like "2 => (4 1)" or assign a numerical value with "4 1" results in syntax errors. Why are these expressions not accepted?
Answer:
This limitation was addressed in PHP version 5.6 with the introduction of constant scalar expressions.
Under this new feature, you can now provide scalar expressions involving numeric and string literals and/or constants in various contexts, including constant and property declarations:
<code class="php">class C { const THREE = TWO + 1; const ONE_THIRD = ONE / self::THREE; }</code>
Therefore, the expressions that previously caused syntax errors are now valid in PHP 5.6 and later:
<code class="php">public $var = array( 1 => 4, 2 => (4+1), ); public $var = 4+1;</code>
These expressions can be evaluated at compile time and do not rely on run-time information, meeting the requirements for property initialization constant values.
The above is the detailed content of Why Can\'t I Initialize PHP Class Properties with Simple Expressions Like \'2 => (4 1)\'?. For more information, please follow other related articles on the PHP Chinese website!