我刚学PHP,我感到困惑的__construct()方法的目的是什么?
如果我能做到这一点:
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;
}
}
那么,为什么有一个构造函数,而不是做呢? :
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;
}
}