PHP Destructor

PHP

PHP Destructor: The __destruct () Function

एक destructor को तब कॉल किया जाता है जब ऑब्जेक्ट नष्ट हो जाती है या स्क्रिप्ट बंद हो जाती है।

अगर हम __destruct() फंक्शन क्रिएट करते हैं तो PHP उसे automatically कॉल कर देता है स्क्रिप्ट के अंत में।

नोट: ध्यान दें कि construct फ़ंक्शन की तरह ही destructor फ़ंक्शन भी दो अंडरस्कोर ( __ ) से शुरू होता है ना की एक से।

नीचे हम एक उदाहरण में destruct फ़ंक्शन देखेंगे।

Example
<?php
class Books{
    // Properties
    public $title;
    public $price;

    // PHP Construction
    function __construct($title, $price){
        $this->title = $title;
        $this->price = $price;
    }

    // Get Destruction
    function __destruct(){
        echo $this->title."<br>" . $this->price."<br><br>";
    }
}

// Objects का निर्माण
$maths = new Books('Encyclopedias of Mathematics',  'Rs.9,393');
$physics = new Books('Fundamentals of Physics',  'Rs.19,765');
$finance = new Books('Rich Dad Poor Dad', 260);
?>
Output
Rich Dad Poor Dad
260

Fundamentals of Physics
Rs.19,765

Encyclopedias of Mathematics
Rs.9,393

ऊपर दिए गए उदाहरण के आउटपुट को आपने गौर से देखा होगा तो समझ गए होंगे कि हमारा आउटपुट उल्टा है यानी कि सबसे नीचे वाला $finance पहले प्रिंट हुआ है और सबसे ऊपर वाला $maths सबसे आखरी में।

ऐसा इसलिए है क्योंकि __distructor() फ़ंक्शन तब कॉल होता है जब स्क्रिप्ट खत्म हो जाती है।

PHP Destructor हमारे लिए कितना फायदेमंद है इसका अंदाजा आप इससे लगा सकते हैं सेम कोड को प्रिंट कराने के लिए हमें get method का इस्तेमाल करना पड़ा था, जिसे आप PHP Constructor चैप्टर में देख सकते हैं।

अब जब हम __distructor() फंक्शन का इस्तेमाल करते हैं तो हमें get method का इस्तेमाल करने की भी जरूरत नहीं है जिससे हमारा बहुत सारा समय और कोड बचता है।

Reference: https://www.php.net/manual/en/language.oop5.decon.php

Article By: Brajlal Prasad
Created on: 23 Apr 2023  868  Views
 Print Article
Report Error

If you want to report an error, or any suggestion please send us an email to [email protected]