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

2019-03-17 23:03发布

问题:

When declaring an array as a class member, which way should it be done?

class Test1 {
    private $paths = array();

    public function __construct() {
        // some code here
    }
}

or

class Test2 {
    private $paths;

    public function __construct() {
        $this->paths = array();
        // some code here
    }
}

Which one is better in terms of good practices and performance? What would you recommend?

回答1:

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)



回答2:

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 here
private $paths = get_paths();

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



回答3:

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.



回答4:

There are no performance implications. Stop obsessing over things that don't matter - concentrate on performance problems that ARE there: measure first, optimize only the top offenders.