Home >Backend Development >PHP Problem >What is the difference between constructor and destructor in php

What is the difference between constructor and destructor in php

王林
王林Original
2020-06-30 11:28:344585browse

The difference between constructors and destructors in php is: 1. The constructor can receive parameters and can be assigned to object properties when creating an object. The destructor cannot take parameters; 2. The constructor is called when creating an object. Function, the destructor is automatically called when the object is destroyed.

What is the difference between constructor and destructor in php

Difference analysis:

Constructor

Classes with a constructor will first call this method each time an object is created.

void __construct ([ mixed $args [, $... ]] )
  • The constructor can receive parameters and can be assigned to object properties when creating the object

  • The constructor can call class methods or other functions

  • The constructor can call the constructor of other classes

Example

<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

Destructor

void __destruct ( void )
  • The destructor is in When the object is destroyed, it is called automatically and cannot be called explicitly.

  • The destructor cannot take parameters

Example:

<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
?>

If you want to know more related knowledge, please visit php中文网.

The above is the detailed content of What is the difference between constructor and destructor in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does php twig mean?Next article:What does php twig mean?