When should I declare variables in a PHP class?

前端 未结 6 1007
小鲜肉
小鲜肉 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:26

    In general variables should be initialized as soon as you have enough info to do it properly.

    If a class variable needs certain info to be sensibly initialized then that info should be passed to the constructor.

    Using PHP's syntax to implicitly declare variables at the point of definition is, IMHO a surefire way to introduce bugs - if your class needs a variable then declare it, and use all of the information hiding that OOP affords you.

提交回复
热议问题