Expressions Allowed in PHP Class Property Declarations
PHP documentation suggests that property declarations in classes can be initialized with constant values, excluding run-time information. However, certain array and mathematical expression initializations seem to be causing syntax errors.
Initializations with Simple Expressions
As per the documentation, simple expressions should be accepted. Here, we examine three variations of array and mathematical expressions:
Accepted:
<code class="php">public $var = array( 1 => 4, 2 => 5, );</code>
Syntax Error:
<code class="php">public $var = array( 1 => 4, 2 => (4+1), );</code>
Syntax Error:
<code class="php">public $var = 4+1;</code>
The first example initializes an array with numeric values and is accepted. However, the second and third examples, utilizing mathematical expressions, both result in syntax errors. This suggests that the limitation extends beyond array syntax to include all calculated expressions.
Constant Scalar Expressions in PHP 5.6
Contrary to the limitations described earlier, PHP 5.6 introduces constant scalar expressions. This new feature allows scalar expressions involving numeric and string literals and constants in contexts where static values were previously required, such as constant and property declarations.
<code class="php">class C { const THREE = TWO + 1; const ONE_THIRD = ONE / self::THREE; const SENTENCE = 'The value of THREE is '.self::THREE; public function f($a = ONE + self::THREE) { return $a; } } echo (new C)->f()."\n"; echo C::SENTENCE;</code>
This code will output:
4 The value of THREE is 3
Therefore, the initial limitations on class property initializations no longer apply in PHP 5.6 and later versions.
The above is the detailed content of Why Do Mathematical Expressions Cause Syntax Errors in PHP Class Property Declarations?. For more information, please follow other related articles on the PHP Chinese website!