PHP has been developing for a long time and many users are familiar with PHP. Here I will share my personal understanding and discuss it with you. Most classes have a special method called constructor. When an object is created, it automatically calls the PHP constructor, that is, when the new keyword is used to instantiate the object, the constructor is automatically called.
The PHP constructor declaration is the same as that of other operations, but its name must be _ construct (). This is a change in PHP5. In previous versions, the name of the constructor must be the same as the class name, which can still be used in PHP5, but it is rarely used now, in this way, the constructor can be made independent of the class name. When the class name changes, you do not need to change the corresponding constructor name. For backward compatibility, if a class does not have a method named _ construct (), PHP will search for a method written in php4 with the same name as the class name. Format: function _ construct ([parameter]) {… ... } Only One constructor can be declared in a class. Instead, the constructor is called only once every time an object is created, so it is usually used to execute some useful initialization tasks. For example, assign an initial value to a property when creating an object.
- // Create a human
-
- 0 class Person
- 0 {
- // The following are the member attributes of a person.
- Var $ name; // name of a person
- Var $ sex; // gender of a person
- Var $ age; // age of a person
- // Define a constructor parameter: name $ name, gender $ sex, and age $ age
- Function _ construct ($ name, $ sex, $ age)
- {
- // Assign the $ name passed in by the constructor to the member attribute $ this->Initial Value assigned by name
- $ This->Name= $ Name;
- // $ Sex passed in through the constructor to the member attribute $ this->Sex assigned Initial Value
- $ This->Sex= $ Sex;
- // The $ age passed in through the constructor gives the Member attributes $ this->Age assigned Initial Value
- $ This->Age= $ Age;
- }
- // How this person speaks
- Function say ()
- {
- Echo "My name is:". $ this->Name. "Gender:". $ this->Sex. "My age is:". $ this->Age ."<Br>";
- }
- }
- // Create three objects $ p1, p2, and $ p3 by using the constructor, and input three different real parameters: name, gender, and age.
- $P1=NewPerson ("Zhang San", "male", 20 );
- $P2=NewPerson ("Li Si", "female", 30 );
- $P3=NewPerson ("Wang Wu", "male", 40 );
- // The following method of accessing the $ p1 object
- $ P1->Say ();
- // The following method of accessing the $ p2 object
- $ P2->Say ();
- // The following method is used to access the $ p3 object.
- $ P3->Say ();
Output result:
My name is John. Gender: male. My age is: 20.
My name is Li Si Gender: Female my age is: 30
My name is: Wang Wu Gender: male my age is: 40