php--constructor function and destructor

Source: Internet
Author: User

PHP5 can use __construct () in a class to define a constructor, a class with constructors that will call the function every time the object is created, so it is often used to do some initialization work when the object is created.

Class Car {   __construct () {       print "constructor is called \ n";   }} $car = new car (); The constructor __construct is called automatically when instantiated, and a string is output here

If you define __construct in a subclass, you do not call the parent class's __construct, and if you need to call the parent class's constructor at the same time, you need to use the parent::__construct () explicit call.

Class Car {   function __construct () {       print "parent class constructor is called \ n";   }} Class Truck extends Car {function __construct () {print "subclass constructor is called \ n";      Parent::__construct (); }} $car = new Truck ();

Similarly, PHP5 supports destructors, which are defined using __destruct () , which refers to functions that are executed when all references to an object are deleted, or when an object is explicitly destroyed.

Class Car {   function __construct () {       print "constructor is called \ n";   }   __destruct () {       print "destructor is called \ n";   }} $car = new car (); When instantiated, the constructor is called after Echo ' is used, ready to destroy the car object \ n '; unset ($car); Destructors are called when destroying

When the PHP code is executed, the object is automatically reclaimed and destroyed, so it is generally not necessary to destroy the object explicitly.

php--constructor function and destructor

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.