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

2019-03-17 23:01发布

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?

4条回答
何必那么认真
2楼-- · 2019-03-17 23:48

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-17 23:51

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)

查看更多
我命由我不由天
4楼-- · 2019-03-17 23:54

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.

查看更多
仙女界的扛把子
5楼-- · 2019-03-17 23:56

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.

查看更多
登录 后发表回答