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!