Sample code sharing for PHP destructors

Source: Internet
Author: User
How to correctly understand PHP destructor

If you declare a function in a class named construct, the function will be treated as a constructor and executed when an object instance is created. Clearly, it is a two underline. Just like any other function, constructors may have parameters or default values. You can define a class to create an object and put its properties all in one statement (statement).

You can also define a function called Destruct, and PHP will call this function before the object is destroyed. It is called a PHP destructor.

Inheritance is a powerful feature of a class. A class (subclass/derived class) can inherit the functionality of another class (parent/base class). The derived class will contain all the properties and methods of the base class, and other properties and methods can be added to the derived class. You can also override the base class's methods and properties. As shown in 3.1.2, you can use the extends keyword to inherit a class.

You might want to know how a constructor is inherited. When they are inherited along with other methods, they are not executed when the object is created.
If you need this feature, you need to use the following:: operator in chapter two. It allows you to point to a namespace. The parent points to the parental namespace, and you can use Parent::construct to invoke the constructor of the parent class.

Some object-oriented languages name constructors after the class. This is true for the first few versions of PHP, which is still valid. That is: If you name a class animal and you create a name in it that is also animal, the The method is the constructor. If a class has both the Construt constructor and the same function as the class name, PHP will treat construct as a constructor. This makes the classes written in the previous PHP version still available. However, the new script (PHP5) should use construct.

This new method of declaring constructors in PHP allows constructors to have a unique name, regardless of the name of the class in which it resides. When you change the name of a class, you do not need to change the name of the constructor.

You might give constructors a way to access the constructor in PHP just like any other class method. Access will affect the ability to instantiate objects from within a certain range. This allows the implementation of some fixed design patterns, such as the singleton mode.

A PHP destructor, as opposed to a constructor. PHP calls them to destroy an object from memory. By default, PHP simply frees the memory occupied by the object's properties and destroys the object-related resources. Destructors allow you to execute arbitrary code after an object is used to clear memory.

When PHP decides that your script is no longer related to the object, the PHP destructor is called. Within the namespace of a function, this occurs at the time of the function return. For global variables, this happens at the end of the script. If you want to explicitly destroy an object, you can assign any other value to the variable that points to the object. Variables are usually assigned on duty to null or called unset.

In the following example, the number of objects instantiated from a class is computed. The counter class adds value from the constructor, reducing the value in the PHP destructor.

Once you have defined a class, you can use new to create an instance of the class. The definition of a class is a design diagram, and an instance is a component placed on an assembly line. New requires the name of the class and returns an instance of the class. If the constructor requires parameters, you should enter the parameters after new.

1 < PHP    2  3 class Counter {private static $count = 0;    4  5 function construct () {self:: $count + +;}    6  7 Function destruct () {self:: $count--;}    8  9 Function GetCount () {return self:: $count;}}   10 11//Establish the first instance of  $c = new Counter ();  //Output 1   print ($c->getcount (). "<br>\n");   18 19//Create a second instance of   $c 2 = new Counter ();   22 23//Output 2   print ($c->getcount (). "<br>\n");   26 27//Destroy instance   $c 2 = NULL;   30 31//Output 1  print ($c->getcount (). "<br>\n");   ?>

When you create a new instance of the PHP destructor, the memory is prepared to store all the properties. Each instance has its own unique set of properties. However, the method is shared by all instances of the class.

PHP 5 allows the developer to define a method as a constructor in a class. Classes with constructors Call this method each time a new object is created, making it ideal for doing some initialization work before using the object.

Note: If a constructor is defined in a subclass, the constructor of its parent class is not implicitly called. To execute the constructor of the parent class, you need to call Parent::construct () in the constructor of the child class . If a subclass does not have a constructor defined, it inherits from the parent class like a normal class method (if it is not defined as private).

Example #1 using the new standard constructor

<?phpclass BaseClass {  function construct () {       print "in BaseClass constructor\n";   }} Class Subclass extends BaseClass {   function construct () {       parent::construct ();              Print "in subclass constructor\n";   }} Class Othersubclass extends BaseClass {    //Inherits BaseClass ' s constructor}//in baseclass constructor$obj = new Bas EClass ();//In BaseClass constructor//in subclass constructor$obj = new subclass ();//in BaseClass constructor$obj = new Othersubclass ();? >

For backwards compatibility, if PHP 5 cannot find the construct () function in the class and does not inherit one from the parent class, it will attempt to find the old constructor, which is the function with the same name as the class. So the only thing that can create a compatibility problem is when a method named construct () already in the class is used for other purposes.

Unlike other methods, PHP does not produce an error message when construct () is overwritten with a method that has different parameters from the parent class construct () E_STRICT .

From PHP 5.3.3, in a namespace, a method with the same name as the class name is no longer a constructor. This change does not affect classes that are not in the namespace.

Example #2 Constructors in namespaced classes

<?phpnamespace Foo;class Bar {public    function bar () {        //treated as constructor in PHP 5.3.0-5.3.2        //Trea Ted as regular method as of PHP 5.3.3    }}?>


destructor ¶

void Destruct (void)

PHP 5 introduces the concept of destructors, similar to other object-oriented languages such as C + +. Destructors are removed when all references to an object are deleted or executed when an object is explicitly destroyed.

Example #3 destructor Example

<?phpclass Mydestructableclass {   function construct () {       print "in constructor\n";       $this->name = "Mydestructableclass";   }      function Destruct () {          print "destroying". $this->name. "\ n";   }} $obj = new Mydestructableclass ();? >

As with constructors, the destructor of the parent class is not called by the engine. To execute a destructor for a parent class, you must explicitly call the parent ::d estruct () in the destructor body of the subclass. Also, as with constructors, subclasses inherit the parent class if they do not have a destructor defined by themselves.

Destructors are called even when the script is run with exit (). Calling exit () in the destructor will abort the operation of the rest of the shutdown operation.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.