0

In PHP (v 5.5.9-1ubuntu4.11) I'm not allowed to initialize data members with functions or arrays of functions. These two violate the PHP syntax on a basis of syntax error, unexpected 'function' (T_FUNCTION), expecting ')':

class Foo {
  var $a = array(
    function() {}
  );
}

and:

class Foo {
  var $a = function() {};
}

Nevertheless, this is allowed:

$a = array(function() {});

Why can't I assign functions to data members in classes?

For ease of reproduceability:

echo '<?php class Foo { var $a = array(function() {}); } ?>' | php
echo '<?php class Foo { var $a = function() {}; } ?>' | php
echo '<?php $a = array(function() {}); ?>' | php
Herbert
  • 5,279
  • 5
  • 44
  • 69
  • @rizier123 : even though the answer might be the same, the question differs significantly. – Herbert Sep 01 '15 at 11:16
  • *even though the answer might be the same* Exactly, the answer is the same. – Rizier123 Sep 01 '15 at 11:20
  • The answer is indeed adequate. Nevertheless, the suggested question was not specifically asked for assigning functions. It requires me (OP) to know that there is a difference between initializing a class variable like `var $a = 5;` and `var $a = function() {};`, which I didn't. – Herbert Sep 01 '15 at 11:20
  • (In any case, thank you for the quick answer) – Herbert Sep 01 '15 at 11:25

0 Answers0