Constructor

The constructor is a magic method that is automatically called upon at the instantiation of a new object.

 

Syntax:

public function __construct() {

... code goes here...

}

 

(*note: magic methods start with a double underscore __ and will be discussed below)

 

A class showing a constructor being automatically called upon an object's instantiation:

Save & refresh browser:

An instance of the the 'Dog' class has been instantiated!

 

 

*note: the above code example also uses the __CLASS__ magic constant, which returns the name of the class

 

  • When using inherited classes,¬†PHP initially looks for and if found will use that¬†constructor in the child class
  • If the child class does not have a constructor, PHP will look to the parent, and then the grand parent, until it reaches the top or finds a constructor
  • Only one constructor will be called

Leave a Reply