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

后端 未结 4 1507
猫巷女王i
猫巷女王i 2021-02-07 00:43

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

class Test1 {
    private $paths = array();

    public function __construct() {
                 


        
4条回答
  •  甜味超标
    2021-02-07 01:18

    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.

提交回复
热议问题