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

王林
Release: 2023-03-01 18:54:01
Original
4592 people have browsed it

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 [, $... ]] )
Copy after login
  • 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();
?>
Copy after login

Destructor

void __destruct ( void )
Copy after login
  • 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();
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template