Which is the better approach to initialize php properties?

前端 未结 5 1628
眼角桃花
眼角桃花 2021-02-19 11:35

Here are two way to initialize class variables.

1st Method

class Test {
    private $var1;
    private $var2;

    public function Test($var1,$var1) {
         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 12:19

    I wonder why you have defined your variables as private in the first place. Private members exist for the class itself rather than for use through a public interface. It may be keeping track of some value, which a magic setter method (__set) can change, at any time in the program, as you have it in your second example. If you need your variables to be private (for class only access) then a constructor function __construct($var1,$var2) or __construct($var1="defaultvalue",$var2="defaultvalue"), so in keeping with your first example.

    It would depend on your anticipated states, which you would have planned in state/activtiy diagrams.

    Hope that helps

提交回复
热议问题