PHP - Constructor And Destructor in Hindi




What is Constructor

PHP में Constructor एक विशेष प्रकार के फ़ंक्शन को refers करता है जिसे कक्षा से object formation होने पर automatically कॉल किया जाएगा। PHP Constructor, जब एक वर्ग का नाम और फ़ंक्शन का नाम समान सामान होता है तब फ़ंक्शन को कन्स्ट्रक्टर के रूप में जाना जाता है।

Constructor विशेष प्रकार की विधि है क्योंकि इसका नाम कक्षा के नाम के समान है।

Example

<?php

class X

{

function testX()

{

echo "This is test method of class X";

}

function X()

{

echo "This is user defined constructor of class X"."
"; } } $obj= new X(); $obj->testX(); ?>

Result

Output This is user defined constructor of class X
This is test method of class X

यहां पर हमने testX() विधि called किया है, लेकिन हमने X() विधि को कॉल नहीं किया क्योंकि ऑब्जेक्ट प्रारंभ होने पर इसे automatically कॉल किया जाता है।

What is Destructor

PHP में Destructor एक विशेष प्रकार के फ़ंक्शन को refers करता है, जिसे जब भी ऑब्जेक्ट हटा दिया जाता है या दायरे से बाहर हो जाता है तो स्वचालित रूप से कॉल किया जाएगा

उस समय ऑब्जेक्ट को नष्ट करने के लिए Destructor का उपयोग किया जाता है, automatic कॉल, कॉल प्रदर्शित नहीं किया जा सकता है। destructors के पास पैरामीटर नहीं हो सकते हैं।

Example

<?php

class demo

{

function  __construct()

{

echo  "object is initializing their propertie"."
"; } function work() { echo "Now works is going "."
"; } function __destruct() { echo "after completion the work, object destroyed automatically"; } } $obj= new demo(); $obj->work(); //to check object is destroyed or not echo is_object($obj); ?>

Result

object is initializing their properties
Now works is going
1
after completion the work, object destroyed automatically