开发者

why declare vars in class out site of constructor?

Is there a good reason to declare variables used by a class outside the constructor function first?

class foo { 

    var bar;  // why is this a good practice? (or could it be skipped?)

    public fun开发者_如何学运维ction __construct() {
        $this->foo = 'foobar';
    }
}

I've seen it often, but I'm not sure what it does, as it seems to work fine to leave them out.


Declaring a property outside of the constructor actually declares it.

If you don't, it'll be automatically created when a value is affected to it.


I see at least four major advantages of declaring properties :

  • You can specify whether they are public, protected, or private
    • See the Visibility section in the manual
  • They'll be seen by your IDE, which will be able to use them as suggestions when you type
    For example, here's a screenshot that shows how Eclipse PDT helps when typing :

    why declare vars in class out site of constructor?


    (source: pascal-martin.fr)

  • And you can add some phpdoc on them -- which means they'll appear in your code's documentation (and IDE can also use that to display better suggestions when you type -- see my screenshot)

  • Declaring your properties makes your code easier to read :
    • When taking a look at your class' definition, one will immediately see which properties are used : no need to guess from the constructor (or any other method)
    • Of course, adding the proper phpdoc helps a lot, here, too.


So : yes, even if PHP accepts properties that are not declared, you should declare them.


For protected and private members, you need to declare. For public you can leave, but for better readability, you SHOULD declare every member. And most IDE also uses the declarations for help hint.

Maybe you need it for reflection too, but I don't know if it works without, because I never tried to leave the declaration :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜