tags:

views:

56

answers:

2

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;
    }
}
+3  A: 

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.

cletus
Ah-of course. Makes sense. Thanks! :)
Joel
A: 

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