PHP7 OOPs Constructor

A constructor is a magic method and defined as __construct() within the class. This is definitely at the top of the class. Constructor method is automatically called when a new object is created.

Constructor Example

<?php
    class FirstClass {
        function __construct($personname) {
            echo $personname;
        }	
        function greet(){
            echo ' welcome!';
        }
    }
    $obj = new FirstClass('John'); 
    echo $obj->greet();
?>

Output

John welcome!





PHP Destructor

PHP has destruct magic method to destroy the created constructor. This purpose of the destructor is to free the memory spaces. The destructor is called at the end of the file. It does not have any parameter.

Destructor Example

<?php
    class FirstClass {
        function __construct($personname) {
            echo $personname;
        }	
        function __destruct(){
            echo 'Destroy all the values';
        }
        function greet(){
            echo ' welcome ';
        }
    }
    $obj = new FirstClass('John'); 
    echo $obj->greet();
?>

Output

Welcome John
Destroy the object.







Read more articles


General Knowledge



Learn Popular Language