Php constructors?

hi all,
i am unable to understand php constructors. can someone explain me and whats its usefulness?

So when you call something like:

$v = new Vacuum;

Behind the scenes as the object is booted up so to speak it can do other stuff it depends upon.


class Vaccuum {

function __construct(){
plugintomains();
// might do other stuff here

}

function plugintomains(){
echo 'Vacuum plugged into mains OK!';

}


}

You could also use the constructor to pass in a key piece of information.

$v = new Vacuum(220);


class Vaccuum {

function __construct($volts = '120'){
findcorrectmains($volts);
plugintomains();
// might do other stuff here

}

function plugintomains(){
echo 'Vacuum plugged into mains OK!';

}

function findcorrectmains($volts){
$vs = array(120.220.240);

  if( in_array($volts, $vs){
    echo 'Connecting to mains supply of ' . $volts;

  }else{
    echo 'Connecting to default mains of 240v';

  }
}
}

It is a special method which is automatically called when your object is instantiated.

Lets say you have a class called SomeObject that contains a child object. You have many different types of the child object, and when you instantiate this object, you could potentially make it different from some other instance of SomeObject because the state would be different. Like so:


class SomeObject {
    protected $_anotherObject;
    public function __construct(AnotherObjectClass $anotherObject) {
        $this->_anotherObject = $anotherObject;
    }
}

Its usefulness depends on what you want to do with your code.