Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize class property with an anonymous function

Tags:

php

Why is not possible to initialize a property to a function when you declare the property in php? The following snippit results in a Parse error: syntax error, unexpected T_FUNCTION

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

Yet you can initialize a property to a string, number or other data types?

Edit:

But I can assign a function to a property in the __construct() method. The following does work:

<?php
  class AssignAnonFunctionInConstructor {
    private $someFunc;

    public function __construct() {
      $this->someFunc = function() {
        echo "Does Work";
      };
    }
  }
?>
like image 517
Chris Gow Avatar asked Oct 27 '09 19:10

Chris Gow


Video Answer


1 Answers

Because it is not implemented in PHP.

http://www.php.net/manual/en/language.oop5.properties.php. Quote:

They (properties) are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

You cannot initialize properties like this, functions are not constant values. Hence my original answer "it is not implemented".

Why is it not implemented? That I can only guess - it probably is quite a complex task and nobody has stepped up to implement it. And/or there may not be enough demand for a feature like that.

like image 141
Anti Veeranna Avatar answered Oct 12 '22 11:10

Anti Veeranna