亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP - 是否可以在 __destruct() 方法中使用自定義異常處理程序

PHP - 是否可以在 __destruct() 方法中使用自定義異常處理程序

PHP
慕村9548890 2022-07-29 10:22:33
有沒有辦法在類的方法中使用自定義異常處理程序,而不是默認異常處理程序__destruct?例如:function myExceptionHandler($e){    echo "custom exception handler";    if(is_object($e) && method_exists($e,'getMessage'))        echo $e->getMessage();}set_exception_handler('myExceptionHandler');class MyClass {    public function __construct()    {        // myExceptionHandler handles this exception        //throw new Exception("Exception from " . __METHOD__);    }    public function doStuff()    {        // myExceptionHandler handles this exception        //throw new Exception("Exception from " . __METHOD__);    }    public function __destruct()    {        // default exception handler         throw new Exception("Exception from " . __METHOD__);    }}$myclass = new MyClass();$myclass->doStuff();即使在方法set_exception_handler內調用__destruct,仍使用默認處理程序:    public function __destruct()    {        $callable = function($e)        {            echo "custom exception handler".PHP_EOL;            if(is_object($e) && method_exists($e,'getMessage'))                echo $e->getMessage();        };        set_exception_handler($callable);        throw new Exception("Exception from " . __METHOD__); // default exception handler    }
查看完整描述

2 回答

?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

手冊頁

筆記:

嘗試從析構函數(在腳本終止時調用)拋出異常會導致致命錯誤。

因此,首先在析構函數中使用異??赡苁莻€壞主意。當腳本完成處理拋出的異常時,可能沒有任何代碼。

也許這段代碼最好放在close()類的方法中。


查看完整回答
反對 回復 2022-07-29
?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

也許是這樣的?


<?php


class MyException extends Exception {

    public function __construct() {

        parent::__construct('my exception');

    }

}


class MyClass {

    public function __construct()

    {

        // myExceptionHandler handles this exception

        //throw new Exception("Exception from " . __METHOD__);

    }


    public function doStuff()

    {

        // myExceptionHandler handles this exception

        //throw new Exception("Exception from " . __METHOD__);

    }


    public function __destruct()

    {

        // default exception handler 

        throw new MyException();

    }


}


$myclass = new MyClass();

$myclass->doStuff();


查看完整回答
反對 回復 2022-07-29
  • 2 回答
  • 0 關注
  • 174 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號