"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can PHP Class Properties Be Initialized with Non-Constant Expressions?

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

Published on 2024-11-10
Browse:688

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:

public $var = array(
    1 => 4,
    2 => (4 1), // Syntax error
);

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:

public $var = array(
    1 => 4,
    2 => (4 1),
);

public $var = 4 1;

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3