zoukankan      html  css  js  c++  java
  • PHP面向对象之析构方法 (__destruct())

    析构方法

    • 语法
      • 当对象销毁的时候自动调用
      • 析构函数不可以带参数
    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>';
    ?>
    

    类和对象在内存中的分布

    • 说明
      • 对象的本质是一个复杂的变量
      • 类的本质是一个自定义的复杂数据类型
      • 栈区:运行速度快,体积小,保存基本类型
      • 堆区:运行速度稍慢,体积大,保存复杂类型
      • 实例化的过程就是分配内存空间的过程
      • 对象保存在堆区,将堆区的地址保存到栈区
  • 相关阅读:
    投资理财知识小结1
    iOS中异常处理机制使用小结
    iOS中NSBundle使用小结
    ant design vue a-cascader 级联选择器 数据回显
    hbase数据存储及数据访问原理
    第15章: Prometheus监控Kubernetes资源与应用
    第14章:部署Java网站项目案例
    第13章:Kubernetes 鉴权框架与用户权限分配
    第12章:有状态应用部署
    第11章:Pod数据持久化
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/14117045.html
Copyright © 2011-2022 走看看