Category:PHP Applications (+)
Directory (?) [+]
PHP construction Method __construct ()
The PHP construction Method __construct () allows the constructor to be executed before instantiating a class.
Construction method
The constructor method is a special method in the class. When you use the new operator to create an instance of a class, the constructor method is automatically called, and its name must be __construct ().
only one construction method can be declared in a class, and the constructor is called once every time the object is created, and it cannot be invoked actively , so it is often used to perform some useful initialization tasks. the method has no return value.
Grammar:
function __construct (arg1,arg2,...) { ......}
Example:
<?phpclass person { var $name; var $age; Defines a constructor method that initializes 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 ("Zhang San"); $p 1->say ();? >
To run the example, output:
My name is: Zhang San's age is: 20
In this example, the object properties are initialized by constructing the method.
Tips
PHP does not automatically invoke the constructor of the parent class in the constructor method of this class. To execute the constructor of the parent class, you need to call Parent::__construct () in the constructor method of the child class.
PHP destructor Method __destruct ()
The PHP destructor Method __destruct () allows execution of the execution of the destructor before destroying a class.
destructor method
And the constructor method corresponds to the Destructor method, the destructor allows some operations to be performed before destroying a class or to perform some functions, such as closing a file, releasing a result set, and so on . destructors cannot have any arguments, and their names must be __destruct ().
Grammar:
function __destruct () { ...}
In the example above, we add the following destructor method:
Defines a destructor method function __destruct () { echo "Goodbye". $this->name;}
To run the example again, output:
My name is: Zhang San my age is: 20 goodbye Zhang San
Tips
- like the constructor method, PHP does not automatically call the parent class's destructor in this class. to perform a destructor for 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 construction method must be the same as the class name and there is no destructor.
PHP construction Method __construct ()