Home > Article > Backend Development > What are the constructor and destructor methods in php
The construction method and destructor method in php are __construct and __destruct respectively. The constructor usually does not need to be called by us, but is automatically called when a new object is created.
The operating environment of this article: windows10 system, php 7.3, thinkpad t480 computer.
Construction method is a special method:
1. The name is fixed: _ _construct;
2. This method usually does not need to be called by ourselves, but It will be called automatically when new an object.
3. The main purpose of this method is to set some "initial values" (initialization work) for the object when new an object;
4. The parameters of the constructor are not specified. , usually defined based on actual needs, for the purpose of initializing object attribute data;
Let’s first look at this situation without a constructor:
It can be seen that it is not convenient to initialize the data value of the object's attributes in this way. We can use the construction method to improve it to:
Destruction method (_ _destruct):
Description:
1. The destructor method is a special method with a fixed name: _ _destruct
2. The destructor method is when an object is "destroyed" A method that will be automatically called when " ”;
Related learning video sharing:
php video tutorialThe above is the detailed content of What are the constructor and destructor methods in php. For more information, please follow other related articles on the PHP Chinese website!