Home  >  Article  >  Backend Development  >  Why can\'t you initialize a PHP class property to a function at declaration time?

Why can\'t you initialize a PHP class property to a function at declaration time?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 17:26:44603browse

Why can't you initialize a PHP class property to a function at declaration time?

Why Can't You Initialize a PHP Property to a Function?

When attempting to initialize a PHP class property to a function during its declaration, a "Parse error: syntax error, unexpected T_FUNCTION" error may arise.

<code class="php">class AssignAnonFunction {
    private $someFunc = function() {
        echo "Will Not work";
    };
}</code>

This occurs because PHP does not allow properties to be initialized with non-constant values, such as functions. The PHP manual explains:

"Properties are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration... this initialization must be a constant value... it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated."

Therefore, functions cannot be assigned to properties at declaration time.

However, properties can be initialized with functions using the __construct() method:

<code class="php">class AssignAnonFunctionInConstructor {
    private $someFunc;

    public function __construct() {
        $this->someFunc = function() {
            echo "Does Work";
        };
    }
}</code>

This is possible because the __construct() method is called at runtime, allowing for the assignment of dynamic values, including functions.

The above is the detailed content of Why can\'t you initialize a PHP class property to a function at declaration time?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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