Sunday, November 17, 2024
Google search engine
HomeLanguagesWhat are the __construct() and __destruct() methods in a PHP ?

What are the __construct() and __destruct() methods in a PHP ?

The constructor is the OOPs concept in PHP. It is a method that has the same name as the class name. It is defined inside the class and is used to automatically call when the object is created.
PHP4 provides the constructor method whereas PHP5 provides the magic method __construct and __destruct. This method is automatically called when an object is created or destroyed. This function always starts with two underscores.

__construct() Method: __construct is a public magic method that is used to create and initialize a class object. __construct assigns some property values while creating the object. This method is automatically called when an object is created.

Properties:

  • __construct is a public magic method.
  •  __construct is a method that must have public visibility
  •  __construct method can accept one and more arguments.
  •  __construct method is used to create an object.
  •  __construct method can call the class method or functions
  •  __construct method can call constructors of other classes also.

The constructor will initialize the class properties at the time of object creation. The __construct() method will be called only once when the object of the class is created.

Syntax:

$object_name= new class_name (argument value);

Example:

$subject=new computer(“English”);

Syntax:

function __construct() {
    // Initialize the object properties
}

Approach:

  • Default Constructor:  By default, __construct() method has no parameters. The values passed to the default constructor are default.
  • Parameterized Constructor: In parameterized constructor __construct() method takes one and more parameters. You can provide different values to the parameters.
  • Copy Constructor: In the copy constructor, the __construct() method accepts the address of the other objects as a parameter.
     

Default Constructor: In default constructor, the __construct() method has no parameters. The values passed to the default constructor are default.

Example: Let us take the example of a class “student” that will display a simple message for this class, We will define a constructor without a parameter.  

Constructor without parameter:

PHP




<?php
 
class Student {
    function __construct() {
        print "This is __construct without parameter\n";
        print "Welcome To GeeksforGeek";
    }
}
 
$obj = new Student();
?>


Output:

This is __construct without parameter
Welcome To GeeksforGeek

Constructor with parameter:

Example 2: Let us take another example of a class “student” who has two properties “name” and “surname“. For this class, we will define a constructor with a parameter that will initialize class properties when the object is created.

PHP




<?php
 
class student {
   
    // Class properties
    public $name;
    public $surname;
     
    // constructor with parameter
    public function __construct($name, $surname) {
        $this->name = $name;
        $this->surname = $surname;
    }
 
      // Display student data
    public function display() {
        echo "My name is " . $this->name
              . "<br>Surname is " . $this->surname;
    }
}
     
// Create class object and pass value
$user = new student("john", "biber");
$user->display();   
 
?>


Output:

My name is john
Surname is biber

PHP Destructor: PHP Destructor method is used to destroy objects or release their acquired memory. A destructor is called automatically when the object is created. Usually, it is called at end of the script. The destructor method does not take any arguments, The destructor does not return any data type. This all process is handled by Garbage Collector.

Properties:

  • __destruct() method does not take any parameter.
  • __destruct() method will not have any return type.
  • This method works exactly the opposite of the __construct method in PHP.
  • __destruct gets called automatically at the end of the script.
  • __destruct() method starts with two underscores (__).
  • It is used to de-initialize existing objects.  

Syntax:

function __destruct() {
    // Destroy objects or release memory.
}

Example:

PHP




<?php
 
class student {
   function __construct() {
       echo "This is a constructor<br>";
       echo "Object is initialized in constructor<br>";
    }
   
    function __destruct() {
        echo "This is destruct<br>";
        echo "Object is destroyed in destructor";
    }
}
  
$subject = new student();
 
?>


Output:

This is a constructor
Object is initialized in constructor
This is destruct
Object is destroyed in destructor

Example: Now, let us take an example of a “class” student who has three properties “name”, “surname”, and “favorite website”. For this class, we will define a constructor with a parameter and the destructor will destroy the initialized object.

PHP




<?php
 
class Student {
    public $name;
    public $surname;
    public $website;
    public function __construct($name,
                  $surname, $website) {
        $this -> name = $name;
        $this -> surname = $surname;
        $this -> website = $website;
    }
   
    public function __destruct() {
        echo "My name is {$this -> name} "
            . "<br>Surname is {$this -> surname}";
        echo "<br>My favorite website is"
            . "{$this -> website}";
        echo "<br>Successfully object Destroyed";
    }
}
 
$info = new Student("John","Biber","Geeksforgeek");
 
?>


Output:

My name is John
Surname is Biber
My favorite website is Geeksforgeek
Successfully object Destroyed

Example: Let us create a class “MyClass”.  In the constructor, we will define a new class property and destroy them in the destructor.   

PHP




<?php
 
class MyClass {
    function __construct() {
        echo "You are in constructor<br>";
        $this->name = "MyClass Object";
    }
 
    function __destruct() {
        echo "You are in destructor<br>";
        print "Just Destroyed " . $this->name;
    }
}
 
$obj = new Myclass();
 
?>


Output:

You are in constructor
You are in destructor
Just Destroyed MyClass Object

Conclusion: In the real world, constructors and destructs are very useful as they space in memory. They allow the reusability of code. Overall they are very useful.

RELATED ARTICLES

Most Popular

Recent Comments