search
HomeBackend DevelopmentPHP TutorialPHP object-oriented destructor and object reference

PHP object-oriented destructor and object reference

May 23, 2020 pm 07:12 PM
object referencedestructorobject-oriented

PHP Orthopedic Analysis Function Function and Object Quote


# This article Study Objective:

                    1. Understand the definition of analytic constructor

2. Understand the role of analytic constructor

3. Understand the function of analytic constructor Features

4. Master the concept and characteristics of object reference assignment

(1), destructor

1, definition:It is a special function

                                                                                                                       

public function destruct(){}

##2. Function

: Clean up objects and release memory

3. Features:

1. Automatic execution instead of manual call

2. Once a class defines a destructor, it will be executed before the program ends Destroy all instance objects under this class

        3. Executed at the last moment before the end of the application, unless there are some special circumstances, such as point 4, or it will be automatically executed after the object's life cycle ends

4. Once we manually destroy an object, the system will automatically trigger the destructor of the object

special attention: If the object is still cited by other objects, if the object is still cited by other objects, it is cited by other objects, and if the object is still referenced by other objects, it is cited by other objects, and if the object is still cited by other objects, Its destructor will not be triggered

      5. Executed before the end of the object’s life cycle

          6. At the last moment before the end of the application, the object that has not been destroyed will be destroyed , the object that has been destroyed will not be destroyed again

It can be further concluded that the destructor of an object can only be executed once and will not be executed multiple times

7. In php, if we If you do not define a destructor for the class, PHP will automatically create a destructor for the class, and then call the default destructor before the end of the program. However, once the destructor is defined, it will Execute the destructor we write

执 执 We can write our business code in our own destructor

. For example, if the printer resource is used by the program, we can release the printer before the object is destroyed. Resource

The relevant code is as follows:

<?php

 class NbaPlayer{
   
    public $name  = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重
    public $team = "";//团队
    public $playerName = "";//球员号码

    
    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    //析构函数
    public function __destruct(){
        echo "销毁对象".$this->name."<br/>";
    }
   
   //跑步
    public function run(){
        echo "跑步中<br/>";
    }
    //跳跃
    public function jump(){
        echo "跳跃<br/>";
    }
    //运球
    public function dribble(){
        echo "运球<br/>";
    } 
    //传球
    public function pass(){
        echo "传球<br/>";
    }
    //投篮
    public function shoot(){
        echo "投篮<br/>";
    }
    //扣篮
    public function dunk(){
        echo "扣篮<br/>";
    }

 }
 //创建乔丹对象
$jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");
//输出乔丹对象
echo "名称= ".$jordon->name."<br/>";
//让乔丹跑步
$jordon->run();

//创建科比对象
$kobe = new NbaPlayer("科比","2米","93公斤","湖人","24");
//创建詹姆斯对象
$james = new NbaPlayer("詹姆斯","2.03米","120公斤","热火","6");
$james1 = new NbaPlayer("詹姆斯1","2.03米","120公斤","热火","6");
$james2 = new NbaPlayer("詹姆斯2","2.03米","120公斤","热火","6");

$jordon = null;//手动的销毁了对象 ,此时乔丹对象的析构函数将会被触发

$kobe = null;//手动的销毁了对象 ,此时科比对象的析构函数将会被触发


echo "<b>程序结束完毕</b><br/>";
?>

Next, I modify the code as follows, add a Mysql database connection class, and then call it in the NbaPlayer constructorThis is Mysql.class.php, which defines a destructor

<?php
//数据库类
class Mysql{
    //定义属性
    public $conn = "";
    //构造函数
    public function __construct( ){
        //初始化行为 初始化方法
        $this->initConn();
    }
    //析构函数 销毁数据库连接
    public function __destruct(){
        //销毁连接
        if( $this->conn ){
            mysqli_close( $this->conn );
            echo "销毁了连接<br/>";
        }
    }
    
    //定义方法
    //创建公共的方法 获取数据库连接
    public function initConn(){
        $config = Array(
            "hostname"=>"127.0.0.1",
            "database"=>"Nbaplayer",
            "username"=>"root",
            "password"=>"root"
        );
        $this->conn = mysqli_connect( $config[&#39;hostname&#39;],$config[&#39;username&#39;] ,$config[&#39;password&#39;],
                $config[&#39;database&#39;]);
    }
}
?>

Next, I will define an NbaPlayer class, but in order to highlight the key points, I will abbreviate the NbaPlayer class as follows:

<?php
 require_once "Mysql.class.php";
 class NbaPlayer{
   
    public $name  = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重
    public $team = "";//团队
    public $playerName = "";//球员号码
    public $conn = "";//添加一个数据库连接属性

    
    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        //初始化数据库连接属性
        $mysql = new Mysql();
        $this->conn = $mysql->conn;
        
    }
    //新增获取所有Nba球员的方法
     public function getAll(){
         //创建数据库连接
        $conn = $this->conn;
        //写sql
        $sql = " select * from ".$this->tableName;
        //执行sql
        $result = mysqli_query( $conn,$sql );
        //获取数据
        // mysqli_fetch_all($result)//特点:不会包含字段名
        $list = Array();
        while( $row = mysqli_fetch_assoc(  $result ) ){
            $list[] = $row;
        }
        //返回数据
        return $list;
     }

 }
 //创建乔丹对象
$jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");

$list = $jordon->getAll();

echo "<b>程序结束完毕</b><br/>";
?>
When you run, you will find the error and you will find that the connection has been destroyed, before the getAll function is called, that is, once instantiated $jordon = new NbaPlayer(" Jordan","1.98 meters","98 kg","Bull","23");

The database connection object is destroyed. In fact, if you go to debug, you will find that the constructor The mysql object in is actually destroyed after the last} of the constructor of the NbaPlayer class is executed. Why?


This actually involves the issue of variable scope, because the mysql object is in It is defined in the constructor, so it cannot be accessed from the outside, so once the constructor is executed, the system will think that it is no longer useful, so it will

clean it up and execute its Destructor, so when you finally call the getAll method, the database connection has already been disconnected, and naturally you can no longer execute sql.

In fact, if you want to solve this problem, you need to understand the object reference. We This problem can be solved by combining object references. Next, let’s first understand object references

(2) and object references

Summary:

        1、变量1=变量2=对象 会创建对象的2个独立引用,但是他们指向的还是同一个对象,所以还是会互相影响

        2、变量1=&变量2 只会创建对象的一个引用,因为它们使用同一个对象引用

        3、一个对象有没有用,就要看它是否完全没有被引用了,如果没有任何变量引用它,它就真的没用了,

            才会被销毁,进而它的析构函数才会得以执行

       4、变量1=clone 变量2=对象,不会创建对象的新引用,而是仿造了一个新的该对象,具有该对象通用的属性和方法

    相关代码如下:

<?php

 class NbaPlayer{
   
    public $name  = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重
    public $team = "";//团队
    public $playerName = "";//球员号码

    
    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    public function __destruct(){
        echo "销毁对象".$this->name."<br/>";
    }
   
   //跑步
    public function run(){
        echo "跑步中<br/>";
    }
    //跳跃
    public function jump(){
        echo "跳跃<br/>";
    }
    //运球
    public function dribble(){
        echo "运球<br/>";
    } 
    //传球
    public function pass(){
        echo "传球<br/>";
    }
    //投篮
    public function shoot(){
        echo "投篮<br/>";
    }
    //扣篮
    public function dunk(){
        echo "扣篮<br/>";
    }

 }
 //创建乔丹对象
$jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");
//输出乔丹对象
echo "名称= ".$jordon->name."<br/>";
//让乔丹跑步
$jordon->run();

//创建科比对象
$kobe = new NbaPlayer("科比","2米","93公斤","湖人","24");
//创建詹姆斯对象
$james = new NbaPlayer("詹姆斯","2.03米","120公斤","热火","6");
$james1 = new NbaPlayer("詹姆斯1","2.03米","120公斤","热火","6");
$james2 = new NbaPlayer("詹姆斯2","2.03米","120公斤","热火","6");

 $jordon1 = $jordon;//&符号表示左边对象和右边对象其实就是一个对象
 $jordon = null;//手动的销毁了对象 


echo "<b>程序结束完毕</b><br/>";
?>

 重点解析:本来不加$jordon1 = $jordon;当程序执行到$jordon=null,乔丹对象的析构函数将会被执行,也就是说 “销毁对象乔丹”在“程序结束完毕” 前显示
但是加了这句以后,你会发现执行到$jordon=null的时候,乔丹对象的析构函数并没有马上执行,而是到应用程序结束后才被系统自动执行 ,也就是说

“销毁对象乔丹”在“程序结束完毕” 后显示

为什么会这样:

接下来就来具体分析$jordon1 = $jordon 这行代码到底让系统做了什么事情

PHP object-oriented destructor and object reference

结合上面的代码,其实我们写的代码顺序是

$jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");

$jordon1 = $jordon;

那么$jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");

说明就是

1、创建了乔丹对象

2、创建了一个变量,变量名叫jordon

3、创了一个乔丹对象的独立引用,就是上图的箭头

然后$jordon1 = $jordon;

说明就是

1、创建了一个新的变量,名叫jordon1

2、又创建了一个乔丹对象的独立引用,就是上图的第二个箭头

那么说明 乔丹对象此时被两个变量引用,当我们$jordon=null 的时候,乔丹对象还被jordon1变量引用,所以此时乔丹对象还有用,还有用就不能当做垃圾清理掉,

所以这就可以解释上面的问题,乔丹对象 在最后 才会被系统销毁,所以要看一个对象是否有用,要看它到底还存不存在变量引用,如果完全不存在变量引用了,那么这个

对象才可以被视作完全无用,它的析构函数才会被执行

好这是对象引用赋值的一种形式,还有另外一种 就是 =& 

代码如下:

<?php

 class NbaPlayer{
   
    public $name  = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重
    public $team = "";//团队
    public $playerName = "";//球员号码

    
    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    public function __destruct(){
        echo "销毁对象".$this->name."<br/>";
    }
   
   //跑步
    public function run(){
        echo "跑步中<br/>";
    }
    //跳跃
    public function jump(){
        echo "跳跃<br/>";
    }
    //运球
    public function dribble(){
        echo "运球<br/>";
    } 
    //传球
    public function pass(){
        echo "传球<br/>";
    }
    //投篮
    public function shoot(){
        echo "投篮<br/>";
    }
    //扣篮
    public function dunk(){
        echo "扣篮<br/>";
    }

 }
 //创建乔丹对象
$jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");
//输出乔丹对象
echo "名称= ".$jordon->name."<br/>";
//让乔丹跑步
$jordon->run();

//创建科比对象
$kobe = new NbaPlayer("科比","2米","93公斤","湖人","24");
//创建詹姆斯对象
$james = new NbaPlayer("詹姆斯","2.03米","120公斤","热火","6");
$james1 = new NbaPlayer("詹姆斯1","2.03米","120公斤","热火","6");
$james2 = new NbaPlayer("詹姆斯2","2.03米","120公斤","热火","6");

 $jordon1 = &$jordon;//&符号表示左边对象和右边对象其实就是一个对象
 $jordon = null;//手动的销毁了对象 


echo "<b>程序结束完毕</b><br/>";
?>

当我们把上面的代码仅仅加上一个 &,也就是把$jordon1 = $jordon 改成 $jordon1 =& $jordon,你会发现结果又变了

变成什么呢,就是当执行$jordon=null的时候,乔丹对象的析构函数还是被执行了,为什么呢

我们再来看下 $jordon1 = & $jordon 做了什么事情

PHP object-oriented destructor and object reference

系统所做事情如下:

1、创建变量,jordon1

2、然后不会再次创建乔丹对象引用,$jordon1通过$jordon变量来使用同一个对象引用来访问乔丹对象

   所以此时乔丹对象,只有一个对象引用,不是2个,所以当我们$jordon=null的时候,其实就是销毁了那唯一的对象引用,进而导致乔丹对象完全没有了对象引用,所以他的析构函数此时会被触发执行

     不管是$jordon1=$jordon 还是 $jordon1=&jordon ,修改任意变量里面的名称,都会导致另外变量的名称被修改掉,因为他们都是引用的同一个乔丹对象

其实对象赋值,除了上面2种方式外,还有第三种,就是 clone(浅复制) ,也就是比如$jordon1 = clone $jordon;

那这样的赋值方式它究竟又是什么意思呢,其实相当于 仿造了 一个乔丹对象

接下来我们通过代码演示

<?php

 class NbaPlayer{
   
    public $name  = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重
    public $team = "";//团队
    public $playerName = "";//球员号码

    
    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        // echo "构造函数执行了,当前对象是{$this->name}<br/>";
    }
    public function __destruct(){
        echo "销毁了对象".$this->name."<br/>";
    }
   
   //跑步
    public function run(){
        echo "跑步中<br/>";
    }
    //跳跃
    public function jump(){
        echo "跳跃<br/>";
    }
    //运球
    public function dribble(){
        echo "运球<br/>";
    } 
    //传球
    public function pass(){
        echo "传球<br/>";
    }
    //投篮
    public function shoot(){
        echo "投篮<br/>";
    }
    //扣篮
    public function dunk(){
        echo "扣篮<br/>";
    }

 }
 //创建乔丹对象
$jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");

$jordon1 = clone $jordon;
$jordon1 = null;
$jordon = null;

echo "应用程序结束<br/>";


?>

执行结果如下:

PHP object-oriented destructor and object reference

所以$jordon1=clone $jordon;其实就是 仿造了一个乔丹对象,拥有和乔丹对象一样的属性和方法

到目前为止,我们了解了对象引用,那么结合对象引用,我们如何解决最开始的那个问题呢?

大家思考一下再看下面的解决方案

....................................

好,接下来我们来看上面我们遇到的问题

问题是:mysql对象在构造函数执行完毕后,就被销毁了,导致后面getAll函数里的数据库连接无法使用

解决思路:

1.mysql对象在构造函数执行完成后,就被销毁了,说明mysql对象此时没有了对象引用

2.那我们就要让他在构造函数执行完成后,依然存在对象引用,那么mysql对象就还有用,还有用就不会被销毁

3.在构造函数里,创建mysql对象的引用,让它在构造函数执行完成后,这个引用依然存在

4.我们可以定义个类的新属性比如$mysql,然后让$this->mysql = $mysql;这样就创建了一个mysql对象的独立引用,而且当构造函数执行完成后

类的mysql属性还有用,所以这个对象引用还有用,进而mysql对象还有用,就不会被销毁

具体代码如下:

<?php
 require_once "Mysql.class.php";
 class NbaPlayer{
   
    public $name  = "";//姓名
    public $height = "";//身高
    public $weight = "";//体重
    public $team = "";//团队
    public $playerName = "";//球员号码
    public $conn = "";//添加一个数据库连接属性
    public $mysql = "";//新增一个mysql属性

    
    public function __construct( $name,$height,$weight,$team,$playerName ){
        $this->name = $name;
        $this->height=$height;
        $this->weight = $weight;
        $this->team = $team;
        $this->playName = $playerName;
        //初始化数据库连接属性
        $mysql = new Mysql();
        $this->conn = $mysql->conn;
        //解决问题的重点代码
        $this->mysql = $mysql;//加了这行代码,getAll中的conn 数据库连接就不会销毁
        
    }
    //新增获取所有Nba球员的方法
     public function getAll(){
         //创建数据库连接
        $conn = $this->conn;
        //写sql
        $sql = " select * from ".$this->tableName;
        //执行sql
        $result = mysqli_query( $conn,$sql );
        //获取数据
        // mysqli_fetch_all($result)//特点:不会包含字段名
        $list = Array();
        while( $row = mysqli_fetch_assoc(  $result ) ){
            $list[] = $row;
        }
        //返回数据
        return $list;
     }

 }
 //创建乔丹对象
$jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23");

$list = $jordon->getAll();

echo "<b>程序结束完毕</b><br/>";
?>

好了,最后我们再稍微做下总结:

1、了解了析构函数的定义,它其实就是一个特殊函数

2、了解了析构函数的作用,就是8个字,清理对象,释放内存

3、了解了析构函数的特点,特点有点多,主要7点

4、知道了对象引用的3种赋值方式,一个是=一个是=&,还有一个是clone

The above is the detailed content of PHP object-oriented destructor and object reference. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools