首頁  >  文章  >  後端開發  >  PHP 中的析構函數

PHP 中的析構函數

WBOY
WBOY原創
2024-08-29 12:42:16393瀏覽

析構函數是一個函數,用於刪除由給定類別的建構函數所建立的物件實例,作為其功能特性的一部分。每當 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();

輸出:

PHP 中的析構函數

範例#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();
?>

輸出:

PHP 中的析構函數

範例 #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;
?>

輸出:

PHP 中的析構函數

如程式碼所述,如果我們取消註解腳本中心的 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();
?>

輸出:

PHP 中的析構函數

如果未建立 test_doc.txt,則會拋出以下警告。

PHP 中的析構函數

析構函數的優點

  • 析構函式有助於釋放記憶體分配,從而確保建構函式新建立的物件存在所需的空間,或為任何其他任務釋放資源。
  • 確保所有任務高效運行,因為它負責清理過程。
  • 在分配許多變數和結構的情況下,使用析構函數將有助於透過釋放內部資源來防止記憶體洩漏。
  • 它負責靜態變數和局部變數。

析構函數的限制

  • 析構函式不能接受任何參數,也不會給出任何回傳值(甚至沒有 void)。
  • 不允許透過析構函數進行繼承
  • 析構函數不一定是靜態的
  • 引用析構函數的位址是不可能的
  • 屬於包含析構函數的類別的物件不允許成為聯合體成員。
  • 析構函式必須具有公共存取權限。

結論

如我們所見,析構函數與建構子完全相反,用於在物件使用完成後銷毀對象,並且在程式碼中不再需要。從而確保它清理不需要的資源,為未來的資源留出空間。這是透過宣告 __destruct() 函數來完成的,PHP 將在腳本末尾自動呼叫該函數。

以上是PHP 中的析構函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn