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

Mary-Kate Olsen
Release: 2024-10-25 17:26:44
Original
602 people have browsed it

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

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

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!

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!