Tuesday, 23 July 2019

Constructor, Destructor Functions and Function Overriding

Constructor
Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behavior, by initializing many things through constructor functions. PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.

Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.
eg:-function __construct( $par1, $par2 ) 
{
   $this->price = $par1;
   $this->title = $par2;
}
Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below −
Eg:-<?php
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
?>
This will produce the following result −
  Physics for High School
  Advanced Chemistry
  Algebra
  10
  15
  7

Destructor
Like a constructor function you can define a destructor function using function__destruct(). You can release all the resources with-in a destructor.

Inheritance
PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows −
Syntax:-class Child extends Parent 
{
   <definition body>
}
The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics −
  • Automatically has all the member variable declarations of the parent class.
  • Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the requirement.
Eg:-<?php
class Novel extends Books 
{
   var publisher;
      function setPublisher($par)
{
      $this->publisher = $par;
   }
      function getPublisher()
{
      echo $this->publisher. "<br />";
   }
}
?>
Now apart from inherited functions, class Novel keeps two additional member functions.

Function Overriding
Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.
In the following example getPrice and getTitle functions are overridden to return some values.
<?php
function getPrice() 
{
   echo $this->price . "<br/>";
   return $this->price;
}
function getTitle()
{
   echo $this->title . "<br/>";
   return $this->title;
}
?>

0 comments

Post a Comment