【发布时间】:2010-05-29 04:08:32
【问题描述】:
我刚学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;
}
}
【问题讨论】:
标签: php oop class constructor