關於php解構函式__destruct()的問題

來源:互聯網
上載者:User

標籤:

1、背景:在一次輸出錯誤資訊,引入Componets\下的ErrorCode的類檔案報錯,報錯的資訊是該類找不到;然而那個類檔案明明存在的阿,怎麼會報錯呢?

2、解決過程:看類載入器如何載入該類。通過架構的入口檔案,一步步地找到載入類,看到類載入器中輸出的類名路徑是正確的(相對路徑),而載入類是仍然不存在,並且使用了file_exists函數判斷該檔案,發現該檔案也不存在,這樣自己百思不得其解。

過段時間,感覺任何在__destruct()函數建立對象是否都會報錯呢?於是實驗,感覺果真如此,自己以為找到原因了。但是為什麼在__destruct函數建立對象會報錯呢?難道真的不能夠在__destruct()中建立函數嗎?感覺這個理論不太成立。於是進行了這樣的實驗:

 1 <?php 2 class Img{ 3     public function info(){ 4         echo ‘I am a Img Class!‘; 5     } 6 } 7  8 class Test{ 9     public function __construct(){10         11     }12     13     public function info(){14         echo ‘I am a Test Class!‘;15     }16     17     public function __destruct(){18         $img = new Img();19         $img->info();20     }21 }22 23 $test = new Test();24 $test->info();

建立對象成功,那麼說明__destruct()函數是可以建立對象的。那麼是否是__destruct()函數不能夠引入檔案,於是

分兩個檔案

一個是Img.class.php檔案

1 <?php2 class Img{3     public function info(){4         echo ‘I am a Img Class!‘;5     }6 }

另一個是test.php檔案

<?phpclass Test{    public function __construct(){            }        public function info(){        echo ‘I am a Test Class!‘;    }        public function __destruct(){        require ‘./Img.class.php‘;            $img = new Img();        $img->info();    }}$test = new Test();$test->info();

結果果真如此,在__destruct()函數中引入類檔案是不行的。那麼為什麼如此呢?

參考這篇文章:http://tieba.baidu.com/p/4529490669

原來__destruct()函數調用時目錄已經發生變化,所以造成載入不了類檔案。

要解決的方法是:使用絕對路徑就可以了。

test.php檔案的代碼這樣:

 1 <?php 2 class Test{ 3     public function __construct(){ 4          5     } 6      7     public function info(){ 8         echo ‘I am a Test Class!‘; 9         echo ‘<br>‘;10         echo getcwd();11     }12     13     public function __destruct(){14         //require ‘./Img.class.php‘;15         require "D:\\wamp\\www\\img\\Img.class.php";16         $img = new Img();17         $img->info();18         echo ‘<br>‘;19         echo getcwd();20     }21 }22 23 $test = new Test();24 $test->info();

 

關於php解構函式__destruct()的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.