In the secrets of Classes article 1, we mentioned the example of assigning an initial value to a property. Each instance of a class may have a different initial value. Can we assign attributes together when the instance is created?
Sure, that’s the constructor we’re going to talk about today.
Basic knowledge of
A constructor is a special member method that initializes the properties of an object when it is created. When creating the constructor, note that there are two underscores:
function __construct($parameters,....) {statements}
Its basic rules:
-
It is performed automatically each time an object is created and can assign initial values to member variables and perform other initialization operations, such as printing greetings.
-
PHP states that there can be only one constructor per class.
-
Because of its meaning, constructors cannot be defined as static, so they cannot be called directly outside the class, but they can be called by other member methods.
Let’s look at a typical constructor:
class Sport2 { public ? string $name; public $sex; public ? $weight; function __construct(? string $name, protected $age, ? int $weight, $sex='male') { $this->name=$name; $this->sex=$sex; $this->age=$age; $this->weight=$weight; Echo 'object initialization complete '; } function showMe() {self::__construct('test',5,10); // The constructor can be called from other member methods; } } $player2=new Test1('Snow',35, 88); $player2->shouMe(); $player2->shouMe();Copy the code
From the above example, we can see several uses of the constructor:
-
When we define a property, we can put the question mark before the property? Since PHP 7.1.0, type declarations are allowed to be preceded by a question mark (?). Use to declare that the value is allowed to be of the specified type, or null.
-
A constructor can assign a default value to a property, specify a property data type, and add new properties.
-
You can also specify visibility for new properties, but if the original property is already visible, you cannot change it.
-
When the object is created, the constructor arguments are called in parentheses after the class name.
-
Other member methods can call the constructor.
Constructor inheritance
Let’s look at the relationship between a class constructor and a superclass constructor by example:
Class BaseClass {function __construct(protected $a, int $b) {print "BaseClass\n"; } class SubClass extends BaseClass {function __construct($a) {parent::__construct(5,5); // Call the superclass constructor print "SubClass\n"; }} class OtherSubClass extends BaseClass {// SubClass extends BaseClass {$obj1 = new SubClass(); BaseClassSubClass $obj2 = new OtherSubClass(5,9); //BaseClassCopy the code
From the above example, we can see that:
-
When a subclass object is created, PHP uses the subclass’s own constructor first.
-
If a subclass does not have its own constructor, PHP calls the constructor in the superclass.
-
Subclass constructors can set arbitrary parameters and method bodies, and are not restricted by superclass constructors. This is different from the rewrites we talked about before. It can be understood that the constructors of the subclass and superclass are independent.
How do I implement multiple constructors in a class?
We mentioned earlier that there can be only one constructor per class. In some cases, however, you need to implement different ways of constructing objects for different situations. In addition to subclasses, we can also use static methods.
Here’s an example:
class Product { private ? int $id; // The data type is preceded by? Is it either an int or null private? string $name; // Set the constructor to private or protected to prevent additional calls. private function __construct(? int $id = null, ? string $name = null) { $this->id = $id; $this->name = $name; } public static function fromBasicData(int $id, string $name) { $new = new static($id, $name); // Insert the user input into the constructor and create a new object; return $new; // Return the new object; } //static refers to the class of the calling object; public static function fromArray(array $arr) { $data = $arr; return new static($data['id'], $data['name']); } public static function fromString(string $stringvar){$data = explode('@',$stringvar); $new = new static(); $new = new static(); $new->id = $data['id']; // Assign attributes again; $new->name = $data['name']; return $new; } } $p1 = Product::fromBasicData(5, 'Widget'); // Call a static method and assign a value directly; $p2 = Product::fromArray($arr); $p3 = Product::fromString($stringvar); // Assign an object from a stringCopy the code
There are two important points in this example:
$new = new static($id, $name)
This statement, in effect, calls the constructor from within the class. Static here is the pronoun and refers to the class calling it, in the example above, Product::. So new static (id,id, id,name) is equivalent to new Product(id,id, id,name). We then assign the new object to $new, as the return value of the function, and assign it to $p1. The latter two examples mean the same thing. PHP calls this “late static binding,” so don’t worry too much about the concept.
The second point is that the constructor __contruct() is set to private. This makes it impossible to create an object outside of the class with new, resulting in an error, and can only be called using a static method of the same class. What if we delete the constructor __contruct()?
In fact, we can rewrite the above example to create objects of the same class by calling different functions. But, you can’t just restrict it to a new object.
Destructor __destruct()
Finally, destructors. While we can create objects, we can also destroy an object. This is where destructors come in. Destructors are often used to “clean up the mess” and free up memory.
Function __destruct() // is double _ {expression; }Copy the code
Destructor rules:
-
Destructors are executed automatically when all references to an object are deleted or when the object is explicitly destroyed.
-
The destructor must be public, otherwise an error will be reported.
-
A subclass can define its own destructor, and PHP will execute the subclass’s destructor first. If the subclass does not define a destructor, it will inherit from the parent class.
-
For a subclass to execute the destruct of its parent class, it must explicitly call parent::__destruct() in the destructor body of the subclass.
Let’s verify the destructor rule:
class Foo4 {
private $name;
private $link;
public function __construct($name) {
$this->name = $name;
}
public function setLink($link){
$this->link = $link;
}
public function __destruct() {
echo 'Destroying: ', $this->name, PHP_EOL;
}
Copy the code
}
$foo = new Foo4('Foo 1'); $bar = new Foo4('Foo 2'); $foo->setLink($bar); $bar->setLink($foo); $foo1 = null; // Reassign the two variables; $bar1 = null; $foo1 = new Foo4('Foo 3'); $bar1 = new Foo4('Foo 4'); echo 'End of script', PHP_EOL; //output: Destroying: Foo 3 Destroying: Foo 4 End of script Destroying: Foo 1 Destroying: Foo 2Copy the code
As you can see from the output, foo and foo, which are mutually referenced, and foo and bar, are not cleared until the program is finished. Foo3 and Foo4 are cleared after they are created. The reason is that foo and foo refer to each other, and even after they are reassigned, their references remain in system memory. This prevents the system from calling the destructor to destroy them until the entire program ends.
Finally, let’s conclude:
- We’ve looked at the basic rules of constructors and illustrated their different uses.
- The inheritance characteristic of constructors is different from that of ordinary member methods.
- And how to wrap a constructor with the static pronoun to implement objects with different input formats
- Finally, there is the destructor, and its inherent mechanism.
Summary is not easy, please do not reprint, otherwise don’t blame the old man you are welcome!
References:
www.php.net PHP official documentation
Zero basic PHP study notes tomorrow technology