Home  >  Article  >  Backend Development  >  Use of constructor __CONSTRUCT() and destructor __DESTRUCT() in php

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

黄舟
黄舟Original
2017-07-02 10:14:262672browse

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”);
? >

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!

Statement:
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