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!