开发者

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

Closed. This question is opinion-based. It is not currently accepting answers. 开发者_开发知识库

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 1 year ago.

Improve this question

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?


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 here
private $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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜