Use of constructor __CONSTRUCT() and destructor __DESTRUCT() in php

黄舟
Release: 2023-03-12 10:38:01
Original
2720 people have browsed it

Defining classes in php is similar to that in java, but the constructor function in php is different. The constructor in PHP uses construct() (two underscores), which ensures that when changing the class name No need to change the constructor name anymore. It also has a destructordestruct(), which is used to destroy instances and release resources.
Once you define a class, you can use new to create an instance of the class. The definition of the class is the design drawing, and the instance is the component placed on the assembly line. New requires the name of the class and returns the name of the class. An example. If the constructor requires parameters, you should enter the parameters after new.

< ?php
class Counter
{
private static $count = 0;

function construct()
{
self::$count++;
}

function destruct()
{
self::$count–;
}

function getCount()
{
return self::$count;
}
}

//建立第一个实例
$c = new Counter();
//此时就调用了构造函数
//输出1
print($c->getCount() . “<br>\n”);

//建立第二个实例
$c2 = new Counter();

//输出2
print($c->getCount() . “<br>\n”);

//销毁实例
$c2 = NULL;
//调用了析构函数
//输出1
print($c->getCount() . “<br>\n”);
? >
Copy after login

The output is: 1,2,1.

The above is the detailed content of Use of constructor __CONSTRUCT() and destructor __DESTRUCT() in php. 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