Which is the better approach to initialize php properties?

前端 未结 5 1604
眼角桃花
眼角桃花 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:22

    My mind is that you should combine both methods.

    Properties that are unavoidable must be present in a construct method.

    For properties that are optional, you should define default value in the construct then create getter/setter.

    And you can create multiple construct methods like for database, in generally, you have:

    myConstructor($dsn)
    myConstructor($dsn, $username, $password)
    myConstructor($dsn, $username, $password, $port)
    myConstructor($dsn, $username, $password, $port, $options)
    

    Then in the "bottom" construct you will set $options then call the "upper" construct that will set the $port and will call "upper" construct... etc...

提交回复
热议问题