Home > Backend Development > PHP Tutorial > Why Do Mathematical Expressions Cause Syntax Errors in PHP Class Property Declarations?

Why Do Mathematical Expressions Cause Syntax Errors in PHP Class Property Declarations?

Linda Hamilton
Release: 2024-10-29 19:11:02
Original
617 people have browsed it

Why Do Mathematical Expressions Cause Syntax Errors in PHP Class Property Declarations?

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>
    Copy after login
  • Syntax Error:

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

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

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

This code will output:

4 The value of THREE is 3
Copy after login

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!

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