Initialize Class Property with an Anonymous Function

Initialize class property with an anonymous function

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.

Using an Anonymous method to populate a property in an object initializer

You want a decimal expression, not a function:

var trades =
from line in sr.Lines()
let items = line.Split('|')
select new Trade
{
Total = Convert.ToDecimal(items[1]) + Convert.ToDecimal(items[2]),
Name = items[3]
};

Is it possible to assign an array with anonymous functions to a class property in PHP?

The problem is the initalization value of your property.

According to the manual on properties:

... They 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.

As an anonymous function cannot be evaluated at compile time, you cannot set it there.

It should work without any problems if you set the value of $this->functions in for example the constructor.



Related Topics



Leave a reply



Submit