Initialize class property with an anonymous function

Chris Gow Source

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";
      };
    }
  }
?>
php

Answers

answered 9 years ago Anti Veeranna #1

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.

answered 9 years ago Travis #2

Closures do not exist in PHP until PHP 5.3 (the latest version). Make sure you have PHP 5.3 if you want to do this.

In earlier versions, you can sort of duplicate this functionality with the create_function() function, somewhat like this:

$someFunc = create_function($args,$code);
$someFunc();

Where $args is a string formatted like "$x,$y,$z" and $code is a string of your PHP code.

comments powered by Disqus