__construct()
is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.
class Person {
public function __construct() {
// Code called for each new Person we create
}
}
$person = new Person();
A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.
class Person {
public $name = '';
public function __construct( $name ) {
$this->name = $name;
}
}
$person = new Person( "Joe" );
echo $person->name;
Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.
Note: I retrieved this from the log of the (at time of this writing) accepted answer, since the original author has issues with having their answer improved.