Constructor and Destructor in php

Object Oriented Programming

Posted on 20 Jun 15 by Vickey
  683



Constructor

PHP5 allows us to declare constructor function.A constructor function automaticallly called when an object created.so we use it for any basic functionality which we need to use in the initialization of application for example database connectivity or setting of UI.

Class BaseConnection
{

 public function __construct() {

    $host = "localhost";
    $username = "root";
    $password = "root";
    $connection = new mysqli($host, $username, $password);
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    } 
    echo "Connected successfully";
  }
  
}
$obj=new BaseConnection(); //create object

if we are using inheritance and the base class and child class both have constructors then the paraent's class constructor will not call automatically so for run paraent constructor we need to use " parent::__construct()"

Class Connection extends BaseConnection
{
    public function __construct() {
        parent::__construct();
    }
}
$obj=new Connection(); //create object

Destructor

The Destructor function caled automatically when object destroy so if we want to destroy any variable or other member of a class then we destroy it in __destruct function
for example after complete all database operation we want to cloase database connection

Class BaseConnection
{
    public function __destruct() {
    
    $connection=mysqli_connect("localhost","user","password","db");
    mysqli_close($connection);
      
   }
}

For call parent  __destruct we use parent::__destruct() same as for __construct

Class Connection extends BaseConnection
{
    public function __destruct() {
        parent::__destruct();
    }
}

 


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com