PHP-面向对象(析构方法)

1.11 析构方法

1.11.1 介绍

当对象销毁的时候自动调用

语法

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>';

运行结果

在这里插入图片描述

1.11.2 计算机的内存管理

计算机内存管理方式:先进先出,先进后出

先进先出的内存管理方式一般用在业务逻辑中,比如秒杀、购票等等

在这里插入图片描述

先进后出是计算机的默认内存管理方式

在这里插入图片描述

1.11.3 思考题

思考题1

<?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');
unset($stu2);
echo '<hr>';
/*
tom出生了
berry出生了
ketty出生了
berry销毁了

ketty销毁了
tom销毁了
*/

思考题2

<?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');
/*
tom出生了
tom销毁了
berry出生了
berry销毁了
ketty出生了
ketty销毁了
*/

思考题3

<?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');
/*
tom出生了
berry出生了
tom销毁了
ketty出生了
berry销毁了
ketty销毁了
*/
发布了1891 篇原创文章 · 获赞 2010 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/105138724