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

    类和对象在内存中的分布

    • 说明
      • 对象的本质是一个复杂的变量
      • 类的本质是一个自定义的复杂数据类型
      • 栈区:运行速度快,体积小,保存基本类型
      • 堆区:运行速度稍慢,体积大,保存复杂类型
      • 实例化的过程就是分配内存空间的过程
      • 对象保存在堆区,将堆区的地址保存到栈区
  • 相关阅读:
    03.通过商品课程初心商品信息
    04.支付宝支付流程
    02.创建商品(表)应用(App)
    01.商品模块表结构
    七牛云上传视频
    Django之序列化器
    Django之抽象基类
    权限系统
    python实现简单工厂模式
    01.git基本操作
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/14117045.html
Copyright © 2011-2022 走看看