Home > Backend Development > PHP Tutorial > Can PHP Class Properties Be Initialized with Non-Constant Expressions?

Can PHP Class Properties Be Initialized with Non-Constant Expressions?

DDD
Release: 2024-10-30 05:41:28
Original
935 people have browsed it

Can PHP Class Properties Be Initialized with Non-Constant Expressions?

PHP Class Initialization Conundrum: Evaluating Expressions in Property Declarations

The PHP documentation dictates that class property declarations can be initialized with constant values. However, users have encountered syntax errors when attempting to initialize arrays with non-constant expressions.

Syntax Error Example:

<code class="php">public $var = array(
    1 => 4,
    2 => (4+1), // Syntax error
);</code>
Copy after login

Underlying Issue:

The error stems from a limitation in PHP 5.5 and earlier versions, where only constant values were allowed in property declarations. This includes values that can be evaluated at compile time. However, the use of calculated expressions, like "4 1," was prohibited.

Resolution in PHP 5.6:

This limitation was lifted in PHP 5.6 with the introduction of constant scalar expressions. This feature allows for the following syntax:

<code class="php">public $var = array(
    1 => 4,
    2 => (4+1),
);

public $var = 4+1;</code>
Copy after login

Conclusion:

The syntax error encountered in earlier versions of PHP when initializing class properties with non-constant expressions has been resolved in PHP 5.6 and later versions. Constant scalar expressions now enable developers to initialize properties with calculated values that can be evaluated at compile time.

The above is the detailed content of Can PHP Class Properties Be Initialized with Non-Constant Expressions?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template