PHP program to demonstrate the use of destructor

Here, we are going to demonstrate the use of destructor in PHP.
Submitted by Nidhi, on November 19, 2020

Here, we will create a class with data members and implement a parameterized constructor and destructor.

Program/Source Code:

The source code to demonstrate the use of the destructor is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the use of destructor.
class Sample
{
    private $num1;
    private $num2;

    public function __construct($n1, $n2)
    {
        $this->num1 = $n1;
        $this->num2 = $n2;
    }

    public function PrintValues()
    {
        echo "Num1: " . $this->num1 . "<br>";
        echo "Num2: " . $this->num2 . "<br>";
    }

    public function __destruct()
    {
        echo "Destructor called";
    }
}

$S = new Sample(30, 40);
$S->PrintValues();
?>

Output:

Num1: 30
Num2: 40
Destructor called

Explanation:

In the above program, we created a class Sample that contains data members $num1 and $num2. The Sample class contains a parameterized constructor using __construct(), destructor using __destruct() and a method PrintValues().

The parameterized constructor is used to initialized the data members, the Destructor of the class is called automatically when the scope of the object gets finished and PrintValues() method is used to print the values of data members.

$S = new Sample(30,40); 

In the above statements, we created the object $S of Sample class then parameterized constructor of Sample class get called automatically and initialized the values of data members.

$S->PrintValues();

In the above statement, we called the PrintValues() method using object $S that will print the values of data members on the webpage.

After that destructor gets called, and prints the "Destructor called" message on the webpage.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.