Why is there a constructor method if you can assign the values to variables?
Posted
by Joel
on Stack Overflow
See other posts from Stack Overflow
or by Joel
Published on 2010-05-29T04:08:32Z
Indexed on
2010/05/29
4:12 UTC
Read the original article
Hit count: 314
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;
}
}
© Stack Overflow or respective owner