2

Creating a class with variables like this works fine:

class Example {
    public static $example = array('simple', 'example');
    // ... 
}

But, if I use a function, when defining the variable, I get an unexpected '(', expecting ')' error:

class Example {
    public static $example = explode(' ', 'simple example');
    // ... 
}

I tried it without the static keyword and still got the same error. Is it possible to use functions, when defining class variables like that? What is the alternative?

1
  • Just make a namespace and put inside of it a global variable .. it will be exactly the same. And you wouldn't be pretending to "do OOP". Commented Apr 20, 2012 at 22:37

3 Answers 3

4

According to the documentation (emphasis mine):

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

Sign up to request clarification or add additional context in comments.

Comments

2

Array is not really a function, but an operator literal, which is why it works. To use a function, just do it with a setter or external to the class:

class Example {
    public static $example = null;
    // ... 

    public static function setE($val) {
       self::$example = $val;
    }
}

Example::$example = explode(' ', 'simple example');

// or

Example::setE(explode(' ', 'nudder example'));

2 Comments

Choosing this answer b/c it came with an alternative way to do it. Thx :]
Sadly, you can't make it final this way, but if you're calling a function on it, it's unlikely you really want it to be anything you compute on the fly anyways.
1

You should be able to do the following,

public static $example = new array('simple','example');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.