Jump to Navigation

032 - OOP Constructors

You often want to initialize certain fields and even trigger the execution of methods found when an object is newly
instantiated. There's nothing wrong with doing so immediately after instantiation.
But it would be easier if this were done for you automatically.Such a mechanism exists in OOP, known as a constructor.

  • Constructors can accept parameters, which are assigned to specific object fields at creation time.
  • Constructors can call class methods or other functions.
  • Class constructors can call on other constructors, including those from the class parent.

function __constructor([argument1, argument2, ......, argumentN])

{

// Class initialization code

}

Example:
Invloking Parent Constructors

class Employee
{
protected $name;
protected $title;

function __constructor()
{
echo "<p>Employee constructor called!</p>"
}
}

class Manager extent Employee
{
function __constructor()
{
parent::__construct();
echo "<p>Manager constructor caled!</p>";
}
$employee new Manager();

-------------------------------------------------------------------------
Employee constructor called!
Manager constructor called!

PHP:


Main menu 2

Story | by Dr. Radut