This article mainly introduces the usage of PHP constructor and destructor, briefly describes the definition and usage of constructor and destructor in PHP, and combines the example form It demonstrates the execution order of constructors and destructors. Friends in need can refer to
. This article explains the usage of PHP constructors and destructors with examples. Share it with everyone for your reference, the details are as follows:
When instantiating a new object, the constructor method and destructor method will be automatically called, if anyInheritance will use the corresponding method of the parent class.
The destructor method will be called in three situations:
① Use unset() to destroy an object. If the object exists Pass the value will not be called;
② Change the value of the object pointed to by the variable;
③ After the PHP program code is finished running.
<?php class base{ public $name; function construct($name){ $this->name = $name; echo 'obj '.$this->name.' have built'.'</br>'.'</br>'; } function destruct(){ echo 'obj '.$this->name.' have destroyed'.'</br>'.'</br>'; } } $a = new base('a'); $b = new base('b'); $c = new base('c'); unset($b); $c = 'd';
The running results are as follows:
obj a have built obj b have built obj c have built obj b have destroyed obj c have destroyed obj a have destroyed
The above is the detailed content of Detailed explanation of the usage of PHP constructor and destructor. For more information, please follow other related articles on the PHP Chinese website!