Home > Article > Backend Development > Detailed explanation of PHP constructor
The content of this article is about the detailed explanation of PHP constructor, which has a certain reference value. Now I share it with everyone. Friends in need can refer to it
// ===Code part 1== =
class Human { public $name = '李四'; public $gender = '男'; } $a = new Human(); $b = new Human(); $c = new Human(); echo $a->name,'<br >'; echo $b->name,'<br >'; echo $c->name,'<br >'; // 三个李四 echo $a->gender,'<br >'; echo $b->gender,'<br >'; echo $c->gender,'<br >'; // 三个男 echo '<hr >';
// ===Notes Part 1===
/*
In the class, there is a constructor,
is used to Used to initialize the object,
Using the constructor, you have the opportunity to manipulate the object,
to change its value
Constructor __construct();
When to use the constructor:
Whenever an object is new, the new object will automatically come into play
*/
// Constructor __construct()
// ===Code part 2===
class People { public function __construct() { $this->name = '李四'; $this->gender = '女'; } public $name = null; public $gender = null; } $a = new People(); $b = new People(); $c = new People(); echo $a->name,'<br >'; echo $b->name,'<br >'; echo $c->name,'<br >'; // 三个李四 echo '<hr >';
// ===Code part 3===
class People2 { public function __construct($name,$gender) {// 通过在构造函数括号内定义变量,传给构造方法 $this->name = $name; $this->gender = $gender; }// 构造函数无法重载 /* public function __construct() { $this->name = 'nobody'; } */ public $name = null; public $gender = null; } $a = new People2('张飞','男'); $b = new People2('空姐','女'); $c = new People2('孙二娘','女'); echo $a->name,'<br >'; echo $b->name,'<br >'; echo $c->name,'<br >'; echo '<hr >';
// Destruction Function __destruct()
// ===Notes Part 2===
/*
Destructor __destruct();
The constructor is When the object is created, the destructor is automatically executed when the object is destroyed. The constructor is automatically executed when the object is destroyed. The constructor is crying when it is born. The destructor is the last words.
1. Explicit destruction, unset, and assignment to null are all acceptable.
2. When PHP executes the code to the last line, all applied memory must be released.
*/
class Human2 { public $name = null; public $gender = null; public function __construct() { echo '出生了<br >'; } public function __destruct() { echo '再见<br >'; } }$a = new Human2(); $b = new Human2(); $c = new Human2(); $d = new Human2(); unset($a); $b = false; $c = null; echo '<hr >';Related recommendations :
Notes on PHP properties and methods
The above is the detailed content of Detailed explanation of PHP constructor. For more information, please follow other related articles on the PHP Chinese website!