析構函數是一個函數,用於刪除由給定類別的建構函數所建立的物件實例,作為其功能特性的一部分。每當 PHP 程式中使用建構函數時,就不會強制需要使用析構函數來補充其功能。但在需要建構函數的程式中使用析構函數被認為是一種很好的做法。此外,該方法並不是專門呼叫執行的,而是在控制項找不到建構函數方法的函數參考時執行。
呼叫析構函數的基本語法:__destruct() 函數,
廣告 該類別中的熱門課程 PHP 開發人員 - 專業化 | 8 門課程系列 | 3次模擬測驗開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
文法:
__destruct ( void ) : void
對於每個要呼叫的析構函數,其前面必須有一個建構函數,如下所示:
<?php class <ANY_CLASS_NAME> { // Declaring a constructor function __construct() { // To initialize required properties } // Declaring a destructor function __destruct() { // To remove reference of an object } } ?>
PHP 中析構函數的工作
析構函數基本上由垃圾收集器管理,當不再需要物件時它會清除該物件。與建構函數相比,它不能接受任何參數作為輸入。
此方法也用於清理資源並釋放記憶體以容納更多記憶體。不能使用析構函數執行重載,且同一類別中只能存在單一析構函數。它的另一個獨特功能是,即使腳本在 exit() 命令的幫助下停止執行,析構函數仍然會被呼叫。此 exit() 將不允許剩餘的關閉方法退出。
PHP 中的析構函數範例
讓我們舉一些例子來更好地理解析構函數:
範例#1
這是一個簡單的範例,我們建立一個基本的建構函數,然後透過呼叫析構函數來銷毀它。
代碼:
<?php class DestructableExample { function __construct() { print "Inside constructor\n"; } function __destruct() { print "Destroying the class " . __CLASS__ . "\n"; } } $obj = new DestructableExample();
輸出:
範例#2
在這個例子中,我們在建構函式中使用了兩個變數;員工的名字和姓氏,然後我們在 PHP 程式碼結束之前透過呼叫析構函式來銷毀物件 Employee。
代碼:
<?php class Employee { // Employee's first name private $emp_fname; // Employee's last name private $emp_lname; // Declaration of constructor public function __construct($emp_fname, $emp_lname) { echo "Initialisation of object as follows...<br/>"; $this->emp_fname = $emp_fname; $this->emp_lname = $emp_lname; } // Declaration of destructor public function __destruct(){ // Here we can clean the resources echo "Removing the Object..."; } // This method is being used to display full name public function showName() { echo "Employee full name is: " . $this->emp_fname . " " . $this->emp_lname . "<br>"; } } // Class object declaration $harry = new Employee("Harry", "Potter"); $harry->showName(); ?>
輸出:
範例 #3
在此範例中,我們將了解如何處理文件 test_doc.txt,該文件是與主文件位於同一工作目錄中的必備文字文件。確保在 test_doc.txt 中包含一些需要作為程式碼的一部分顯示的文字。
fopen是用來開啟檔案的內建函數,fread是用來讀取檔案內容的函數。這裡將呼叫析構函數來關閉/銷毀檔案句柄。
代碼:
<?php header("Content-type: text/plain"); class Example { /** * Declaring an identifier * variable- string */ private $first_name; /** * A reference to another Foo object * variable Foo */ private $setlink; public function __construct($first_name) { $this->first_name = $first_name; } public function setLink(Example $setlink){ $this->setlink = $setlink; } public function __destruct() { echo 'Destroying: ', $this->first_name, PHP_EOL; } } // We are creating 2 objects here $obj1 = new Example('Example 1'); $obj2 = new Example('Example 2'); // Objects are made to point to themselves $obj1->setLink($obj1); $obj2->setLink($obj2); // Destroying their global references $obj1 = null; $obj2 = null; // Since both objects are declared null we cannot access them now and hence they must be destroyed // but since they are not yet destroyed a memory leak may occur as they are still present. // // Garbage collector can be called as shown in below line. Uncomment to check its functionality // gc_collect_cycles(); // Now we create 2 more objects but will not set their references // only the obj1 and obj2 are pointing to them right now $obj1 = new Example('Example 3'); $obj2 = new Example('Example 4'); // Removing their global references $obj1 = null; $obj2 = null; // Now the Example 3 and example 4 cannot be accessed due to no references // for them. Hence the destructor is called automatically // previous to the execution of next line echo 'Script has ended', PHP_EOL; ?>
輸出:
如程式碼所述,如果我們取消註解腳本中心的 gc_collect_cycles() 函數,我們將得到以下輸出:
範例#4
代碼:
<?php class FileHandle{ private $file_handle; private $name; /** * We declare file handle with parameters file name and mode * Using parameter string $name as file name * Using parameter string $fmode as file mode for read, write */ public function __construct($name,$fmode){ $this->name = $name; $this->file_handle = fopen($name, $fmode); } /** * We are closing the file handle */ public function __destruct(){ if($this->file_handle){ fclose($this->file_handle); } } /** * Reading and printing file's content */ public function display(){ echo fread($this->file_handle, filesize($this->name)); } } $fu = new FileHandle('./test_doc.txt', 'r'); $fu->display(); ?>
輸出:
如果未建立 test_doc.txt,則會拋出以下警告。
析構函數的優點
- 析構函式有助於釋放記憶體分配,從而確保建構函式新建立的物件存在所需的空間,或為任何其他任務釋放資源。
- 確保所有任務高效運行,因為它負責清理過程。
- 在分配許多變數和結構的情況下,使用析構函數將有助於透過釋放內部資源來防止記憶體洩漏。
- 它負責靜態變數和局部變數。
析構函數的限制
- 析構函式不能接受任何參數,也不會給出任何回傳值(甚至沒有 void)。
- 不允許透過析構函數進行繼承
- 析構函數不一定是靜態的
- 引用析構函數的位址是不可能的
- 屬於包含析構函數的類別的物件不允許成為聯合體成員。
- 析構函式必須具有公共存取權限。
結論
如我們所見,析構函數與建構子完全相反,用於在物件使用完成後銷毀對象,並且在程式碼中不再需要。從而確保它清理不需要的資源,為未來的資源留出空間。這是透過宣告 __destruct() 函數來完成的,PHP 將在腳本末尾自動呼叫該函數。
以上是PHP 中的析構函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

負載均衡會影響會話管理,但可以通過會話複製、會話粘性和集中式會話存儲解決。 1.會話複製在服務器間複製會話數據。 2.會話粘性將用戶請求定向到同一服務器。 3.集中式會話存儲使用獨立服務器如Redis存儲會話數據,確保數據共享。

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

PHP會話的替代方案包括Cookies、Token-basedAuthentication、Database-basedSessions和Redis/Memcached。 1.Cookies通過在客戶端存儲數據來管理會話,簡單但安全性低。 2.Token-basedAuthentication使用令牌驗證用戶,安全性高但需額外邏輯。 3.Database-basedSessions將數據存儲在數據庫中,擴展性好但可能影響性能。 4.Redis/Memcached使用分佈式緩存提高性能和擴展性,但需額外配

Sessionhijacking是指攻擊者通過獲取用戶的sessionID來冒充用戶。防範方法包括:1)使用HTTPS加密通信;2)驗證sessionID的來源;3)使用安全的sessionID生成算法;4)定期更新sessionID。

本文比較了PHP和ASP.NET,重點是它們對大規模Web應用程序,性能差異和安全功能的適用性。兩者對於大型項目都是可行的,但是PHP是開源和無關的,而ASP.NET,


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3漢化版
中文版,非常好用

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具