Core PHP

A Class Constructor

A constructor provides a way for an object to be created. A constructor can take arguments or it may take none. The constructor function is where the initialization of an object and its default values should take place.

The constructor is defined inside the class definition and looks like a function that is defined with the name __construct. Unlike most other object-oriented languages, only one constructor function is allowed in a PHP class. Despite the function notation, the constructor is called using the new keyword followed by the class name and arguments, as shown.

In the code below, we instantiate two CProphet objects by using "new" with distinct values for each object. The first object represents the prophet Isaiah and the second object represents the last prophet, John the Baptist.

CProphet.php

<?php
  class CProphet {
    var $msName;
    var $msProphecy;

	// Only one constructor is allowed per class
    public function __construct($sName, $sProphecy) {
      $this->msName = $sName;
      $this->msProphecy = $sProphecy;
    }
  }

  $qIsaiah = new CProphet("Isaiah", "Here am I! Send me.");
  echo "Name: " . $qIsaiah->msName . "<br />";
  echo "Prophecy: " . $qIsaiah->msProphecy . "<br /><br />";

  $qJohnTheBaptist = new CProphet("John", "Behold the Lamb of God!");
  echo "Name: " . $qJohnTheBaptist->msName . "<br />";
  echo "Prophecy: " . $qJohnTheBaptist->msProphecy . "<br />";
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.