How to Assign Anonymous Functions to Class Properties in PHP?

Susan Sarandon
Release: 2024-10-26 13:25:02
Original
631 people have browsed it

How to Assign Anonymous Functions to Class Properties in PHP?

Assigning Anonymous Functions to Class Properties in PHP

In PHP, it is not possible to directly initialize a class property to an anonymous function when declaring it. The code snippet below:

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

Generates the error message "Parse error: syntax error, unexpected T_FUNCTION." This is because the PHP language does not allow the initialization of properties with functions during the declaration phase.

Constant Value Initialization Restriction

According to the PHP manual, class properties can only be initialized with constant values during their declaration. A constant value is one that can be evaluated at compile time without relying on runtime information. Functions, however, do not fit this criterion and are therefore not allowed as property initializers during declaration.

Workaround Using Constructor

Despite the inability to initialize properties with anonymous functions during declaration, it is possible to assign functions to properties within the constructor method. Modifying the previous code to the following allows for the assignment:

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

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

The constructor method is called upon object creation, allowing for the assignment of the anonymous function to the property at runtime.

The above is the detailed content of How to Assign Anonymous Functions to Class Properties in PHP?. 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!