Why is there a constructor method if you can assign the values to variables?

≯℡__Kan透↙ 提交于 2019-12-11 07:22:08

问题


I'm just learning PHP, and I'm confused about what the purpose of the __construct() method?

If I can do this:

class Bear {
    // define properties
    public $name = 'Bill';
    public $weight = 200;

    // define methods
    public function eat($units) {
        echo $this->name." is eating ".$units." units of food... <br />";
        $this->weight += $units;
    }
}

Then why do it with a constructor instead? :

class Bear {
    // define properties
    public $name;
    public $weight;

    public function __construct(){

        $this->name = 'Bill';
        $this->weight = 200;
    }
    // define methods
    public function eat($units) {
        echo $this->name." is eating ".$units." units of food... <br />";
        $this->weight += $units;
    }
}

回答1:


Because constructors can do more complicated logic than what you can do in variable initialization. For example:

class Bear {
  private $weight;
  private $colour;

  public __construct($weight, $colour = 'brown') {
    if ($weight < 100) {
      throw new Exception("Weight $weight less than 100");
    }
    if (!$colour) {
      throw new Exception("Colour not specified");
    }
    $this->weight = $weight;
    $this->colour = $colour;
  }

  ...
}

A constructor is optional but can execute arbitrary code.




回答2:


You can give dynamic variables to your class:

with:

public function __construct(name, amount){

    $this->name = name;
    $this->weight = amount;
}

You can use your class for "bill" and "joe" and use different values of amounts.

Also you can make sure that you class will always has all it needs, for example a working database connection: You constructor should always demand all needs:

public function __construct(database_connection){
[...]
}


来源:https://stackoverflow.com/questions/2933750/why-is-there-a-constructor-method-if-you-can-assign-the-values-to-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!