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

    类和对象在内存中的分布

    • 说明
      • 对象的本质是一个复杂的变量
      • 类的本质是一个自定义的复杂数据类型
      • 栈区:运行速度快,体积小,保存基本类型
      • 堆区:运行速度稍慢,体积大,保存复杂类型
      • 实例化的过程就是分配内存空间的过程
      • 对象保存在堆区,将堆区的地址保存到栈区
  • 相关阅读:
    【bzoj2733】永无乡(无旋treap启发式合并 + 并查集)
    【bzoj2002】弹飞绵羊(分块)
    【bzoj2724】蒲公英(分块)
    【最大M子段和】dp + 滚动数组
    【最大连续子段和】单调队列 + 前缀和优化
    【广告印刷】单调队列
    【烽火传递】dp + 单调队列优化
    【志愿者选拔】单调队列、输入优化
    【Sliding Window】单调队列
    【序列操作V】平衡树(无旋treap)
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/14117045.html
Copyright © 2011-2022 走看看