PHP Construction Method __construct ()
the PHP constructor Method __construct () allows the constructor method to be executed before instantiating a class. Construction Method
A construction method is a special method in a class. When you create an instance of a class using the new operator, the constructor is invoked automatically, and the name must be __construct ().
Only one construction method can be declared in a class, but only once when the object is created, the method is called once, and it cannot be invoked actively, so it is usually performed with some useful initialization tasks. The method has no return value.
Grammar:
function __construct (arg1,arg2,...)
{
......
}
Example:
<?php
class Person {
var $name;
var $age;
Defines a constructor to initialize
the assignment function __construct ($name, $age) {
$this->name= $name;
$this->age= $age;
}
function say () {
echo "My name is:". $this->name. " <br/> ";
echo "My Age is:". $this->age;
}
}
$p 1=new person ("John");
$p 1->say ();
? >
Run the example and output:
My name
is: The Age of John is: 20
In this example, the object property is initialized with the constructor method. Tips
PHP does not automatically invoke the constructor method of the parent class in the constructor of this class. To execute the constructor of the parent class, you need to call Parent::__construct () in the constructor method of the subclass. PHP destructor Method __destruct ()
PHP destructor __destruct () allows execution of a destructor to be performed before a class is destroyed. destructor Method
Corresponding to the construction method is the destructor, the destructor allows some of the operations performed before the destruction of a class or some function, such as closing the file, releasing the result set, and so on. Destructors cannot have any arguments, their names must be __destruct ().
Grammar:
function __destruct ()
{
...
}
We add the following destructor to the example above:
Defines a destructor
function __destruct ()
{
echo "Goodbye". $this->name;
}
Run the example again, output:
My name is: John
my age is:
goodbye John
TipsAs with construction methods, PHP does not automatically invoke the parent class's destructor in this class. To perform a destructor of the parent class, you must manually call Parent::__destruct () in the destructor body of the subclass. Attempting to throw an exception in a destructor can result in a fatal error. In the PHP4 version, the name of the constructed method must be the same as the class name, and there is no destructor.