Home > Backend Development > PHP Tutorial > Detailed explanation of the usage of PHP constructor and destructor

Detailed explanation of the usage of PHP constructor and destructor

怪我咯
Release: 2023-03-12 19:50:01
Original
1497 people have browsed it

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 &#39;obj &#39;.$this->name.&#39; have built&#39;.&#39;</br>&#39;.&#39;</br>&#39;;
  }
  function destruct(){
    echo &#39;obj &#39;.$this->name.&#39; have destroyed&#39;.&#39;</br>&#39;.&#39;</br>&#39;;
  }
}
$a = new base(&#39;a&#39;);
$b = new base(&#39;b&#39;);
$c = new base(&#39;c&#39;);
unset($b);
$c = &#39;d&#39;;
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template