PHP5. Two ways of declaring an array as a class member PHP5. Two ways of declaring an array as a class member php php

PHP5. Two ways of declaring an array as a class member


I'd suggest doing this when declaring a class variable. A constructor can be overriden in extending classes, which might result in E_NOTICEs or even E_WARNINGs if any of your functions depend on this variable being an array (even an empty one)


If you are going to populate your array dynamically during initialization, do it in the constructor. If it contains fixed values, do it in the property declaration.

Trying to populate an array dynamically (e.g. by using the return value of a certain function or method) within the declaration results in a parse error:

// Function call is not valid hereprivate $paths = get_paths();

Performance is not a real concern here as each has its own use case.


In general, because I write mostly in other languages besides PHP, I like to declare my instance variables outside of the constructor. This let's me look at the top of a class and get an idea for all properties and their access modifiers without having to read the code.

For example, I really don't like methods like this

// ...// whole bunch of code// ...public function initialize() {    $this->foo = array();    // some other code to add some stuff to foo}

Now, if I just look at the class, I can't be sure there is a variable foo even available. If there is, I don't know if I have access to it from anywhere outside the instance.

If instead I have:

public $foo = array();

at the top of my class, I know that foo is an instance property, and that I can access it from elsewhere.