开发者

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

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 />";
       开发者_如何学Python $this->weight += $units;
    }
}


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.


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){
[...]
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜