If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
जब भी किसी class का Object Create / Destroy होता है तो उस Class के लिए दो method Automatically Run होते है - __construct And __destruct . जिन्हे Constructor और Destructor कहते हैं।
HP में Constructor का principle Java , C++ से थोड़ा different है। Java में सिर्फ Constructor होता है जबकि PHP में Constructor और Destructor दोनों होते हैं।
जब किसी class का Object बनाते हैं तो __construct automatically run होता है। इसे run करने के लिए call करने जरूरत नहीं पड़ती है। लेकिन अगर Class का Object नहीं बना तो __construct method run नहीं होगा।
बाकी Functions / Methods की तरह ही इसमें भी parameters , define कर सकते हैं।
❕ Important
By Default ये Non Static ही होते हैं , इन्हे आप as a static member define नही कर सकते हैं। अगर ऐसा करते हैं तो PHP Fatal Error Generate करती है।
PHP Fatal error: Constructor ClassName::__construct() cannot be static.
File : php_construct.php
<?php
class MyClass
{
function __construct()
{
echo 'Object Initialized';
}
}
new MyClass;
?>
Object Initialized
? PHP में Class का Object बनाते समय ClassName के बाद parenthesis skip कर सकते हैं।
अब अगर आप parameter भी define करना चाहते हो तो class Object बनाते समय उन parameters की value pass करनी पड़ेगी।
For Example :
File : php_construct.php
<?php
class MyClass
{
function __construct($param, $default_param = 'Default Value')
{
echo 'Param : '.$param;
echo '<br>'; /* for line break*/
echo 'Default Parame : '. $default_param;
}
}
new MyClass('Test Param Value');
?>
Param : Test Param Value
Default Parame : Default Value
इसके अलावा अगर आप define की गयी Class Property में Constructor value assign करना चाहते हैं तो simply $this-> का use करके assign कर सकते हैं।
<?php
class MyClass
{
public $fullname;
function __construct($fullname)
{
$this->fullname = $fullname;
}
function getName()
{
echo 'Welcome : '. $this->fullname;
}
}
$obj = new MyClass('Rahul Kumar Verma');
$obj->getName();
?>
__destruct , तब automatically run होता है जब Initialize किया गया Class Object destroy होता है। हालाँकि जब script end होती है तो Class Object destroy हो जाते हैं।
File : php_destruct.php
<?php
class MyClass
{
function __construct()
{
echo 'Object Initialized';;
}
function __destruct()
{
echo '<br>'; /** For line break */
echo 'Object Destroyed';
}
}
new MyClass;
?>
Object Initialized
Object Destroyed
Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.
Get connected with me. :) LinkedIn Twitter Instagram Facebook