Yes, the constructor is called when the object is created.
A small example of constructor utility is
class Bar { // The variable we will be using within our class var $val; // This function is called when someone does $foo = new Bar(); // But this constructor has also an $var within its definition, // So you have to do $foo = new Bar("some data") function __construct($var) { // Assign the $var from the constructor to the $val variable // we defined above $this->val = $var } } $foo = new Bar("baz"); echo $foo->val // baz // You can also do this to see everything defined within the class print_r($foo);
UPDATE: The question also asked why this should be used, an example of a real life is a database class in which you call an object with a username and password and a table to connect to which the constructor will connect. Then you have the functions to do all the work in this database.
Ólafur waage
source share