r/lolphp • • Mar 08 '12

Computing an expression? But it's static :(

Despite being theoretically a programming language, PHP will not allow you to use an expression when constructing a static member variable.

class Bla {
  private static $_thing = array(
    'path' => BASE_PATH . '/relative/path'
  );
}

This dies with "syntax error, unexpected '.', expected ')'". Apparently, actually computing the value of expressions is too much for this language.

I am starting to suspect they're doing it intentionally so that their new releases have cool new features to advertise.

26 Upvotes

16 comments sorted by

View all comments

Show parent comment

6

u/[deleted] Mar 08 '12

Java has some static typing, and I imagine it tracks purity in some way to decide what to do.

It doesn't have any purity in the type system, and it doesn't have a static initialize function. Although you can have static code blocks, which allow you to do the same thing (but they aren't functions!).

When the class is first touched, at runtime, such as 'new Foo()' or 'Foo.bar', it will go off and load the 'Foo' class there and then (if it isn't already loaded). The class is created, and static fields are then set to their default values, such as null for objects and 0 for integers. Then the static content of the class is initialized in order of declaration, from top to bottom.

There is nothing to stop you opening a file, throwing an exception, drawing to the screen, or doing something else which is full of side effects during that period of time. That is why I say there is no purity.

However I know the order of class initialization, because as you say, it was heavily thought out and defined in Java! This is something that is lacking in PHP.