Property Initialization with Anonymous Functions: Why and How?
As mentioned in the code snippet below, initializing a property with an anonymous function during class declaration triggers a "Parse error: syntax error, unexpected T_FUNCTION" in PHP. Yet, assigning functions to properties within constructors is possible, as demonstrated in the second snippet.
// Property initialization with anonymous function error
class AssignAnonFunction {
private $someFunc = function() {
echo "Will Not work";
};
}
// Property initialization in constructor
class AssignAnonFunctionInConstructor {
private $someFunc;
public function __construct() {
$this->someFunc = function() {
echo "Does Work";
};
}
}
The inability to initialize properties directly with anonymous functions stems from PHP's implementation. Properties must be initialized with constant values that are evaluable during compilation, and functions do not meet this criterion.
Despite this limitation, PHP allows the assignment of functions to properties within constructors. This is because constructors are executed at runtime, allowing for dynamic assignments.
While this workaround provides flexibility, the lack of direct property initialization with anonymous functions can be a drawback in certain scenarios. It necessitates additional code and can impact code readability.
Although the reason for this design decision in PHP remains somewhat speculative, possible explanations include the complexity of implementing such a feature and insufficient demand for it.
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