When should I declare variables in a PHP class?

前端 未结 6 1014
小鲜肉
小鲜肉 2020-11-30 03:06

I\'m new to the OOP paradigm, so there\'s probably a simple explanation for this question...

Do you always need to declare public object-wide variables in a class? F

6条回答
  •  隐瞒了意图╮
    2020-11-30 03:41

    You should always declare your member variables and specify their accessibility within your classes. I like to put this information at the end of the class after my functions.

    You should define them as soon as you have enough information to do so. Possibly in the constructor or via setter functions.

    It is important to do this because it makes life much easier for people working with your code. They don't have to guess where different properties are coming from or why they're there. Also, most (if not all) IDEs will not pick up on class variables unless you've declared them somewhere. Code completion/hints are one of the many benefits of IDEs and without declaring your variables, you will render that functionality useless.

提交回复
热议问题