析构方法
- 语法
- 当对象销毁的时候自动调用
- 析构函数不可以带参数
function __destruct(){
}
<?php
class Student {
private $name;
//构造方法
public function __construct($name) {
$this->name= $name;
echo "{$name}出生了<br>";
}
//析构方法
public function __destruct() {
echo "{$this->name}销毁了<br>";
}
}
//测试
$stu1=new Student('tom');
$stu2=new Student('berry');
$stu3=new Student('ketty');
echo '<hr>';
?>
计算机内存管理
-
计算机内存管理方式
- 先进先出,先进后出
- 先进先出的内存管理方式一般用在业务逻辑中,比如秒杀、购票等等
- 先进后出是计算机的默认内存管理方式
-
思考题:先进后出(堆栈)
<?php
class Student {
private $name;
//构造方法
public function __construct($name) {
$this->name= $name;
echo "{$name}出生了<br>";
}
//析构方法
public function __destruct() {
echo "{$this->name}销毁了<br>";
}
}
//测试
$stu1= new Student('tom');
$stu2= new Student('berry');
$stu3= new Student('ketty');
echo '<hr>';
?>
- 思考题:先进先出(队列)
<?php
class Student {
private $name;
//构造方法
public function __construct($name) {
$this->name= $name;
echo "{$name}出生了<br>";
}
//析构方法
public function __destruct() {
echo "{$this->name}销毁了<br>";
}
}
//测试
new Student('tom');
new Student('berry');
new Student('ketty');
echo '<hr>';
?>
- 思考题:???
<?php
class Student {
private $name;
//构造方法
public function __construct($name) {
$this->name= $name;
echo "{$name}出生了<br>";
}
//析构方法
public function __destruct() {
echo "{$this->name}销毁了<br>";
}
}
//测试
$stu= new Student('tom');
$stu= new Student('berry');
$stu= new Student('ketty');
echo '<hr>';
?>
类和对象在内存中的分布
- 说明
- 对象的本质是一个复杂的变量
- 类的本质是一个自定义的复杂数据类型
- 栈区:运行速度快,体积小,保存基本类型
- 堆区:运行速度稍慢,体积大,保存复杂类型
- 实例化的过程就是分配内存空间的过程
- 对象保存在堆区,将堆区的地址保存到栈区