Why Can\'t I Initialize PHP Class Properties with Simple Expressions Like \'2 => (4 1)\'?

Susan Sarandon
Release: 2024-11-01 12:49:58
Original
791 people have browsed it

Why Can't I Initialize PHP Class Properties with Simple Expressions Like (4 1)"? " /> (4 1)"? " />

PHP Class Property Declarations with Simple Expressions

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!