[英]Is it possible in PHP to prevent “Fatal error: Call to undefined function”?
在 PHP 中,有什么方法可以忽略未定義的函數而不是拋出在瀏覽器中可見的致命錯誤?-即致命錯誤:調用未定義的函數
我知道有一種將所有自定義函數包裝在如下條件中的做法,但是有沒有一種編程方式來獲得這種效果?
if (function_exists('my_function')) {
// use my_function() here;
}
不。致命錯誤是致命的。 即使您要編寫自己的錯誤處理程序或使用@
錯誤抑制運算符, E_FATAL
錯誤仍會導致腳本停止執行。
處理這個問題的唯一方法是使用function_exists()
(並且可能是is_callable()
以進行良好的衡量),如上面的示例所示。
圍繞潛在的(可能的?)錯誤進行防御性編碼總是比讓錯誤發生並稍后處理它更好的主意。
編輯- php7 改變了這種行為,未定義的函數/方法是可捕獲的異常。
在 php 7 中,這現在是可能的。
示例代碼:
try {
some_undefined_function_or_method();
} catch (\Error $ex) { // Error is the base class for all internal PHP error exceptions.
var_dump($ex);
}
http://php.net/manual/en/migration70.incompatible.php
許多致命和可恢復的致命錯誤已在 PHP 7 中轉換為異常。這些錯誤異常繼承自 Error 類,該類本身實現了 Throwable 接口(所有異常繼承的新基接口)。
如果您想在處理對象時抑制此錯誤,請使用此函數:
function OM($object, $method_to_run, $param){ //Object method
if(method_exists(get_class($object), $method_to_run)){
$object->$method_to_run($param);
}
}
問候
我們可以隱藏錯誤,但這會登錄 apache 錯誤日志
//設置顯示錯誤為真。
ini_set('display_errors', "0");
//報告除通知外的所有錯誤
ini_set('error_reporting', E_ALL ^ E_NOTICE ^ E_STRICT);
//我們可以使用try catch方法
try {
my_method();
} catch (\Error $ex) { // Error is the base class for all internal PHP error exceptions.
var_dump($ex);
}
//檢查方法是否存在
function_exists()
防止沒有。 但是捕獲並記錄是的,使用 register_shutdown_function()
參見PHP 手冊
function shutDown_handler()
{
$last_error = error_get_last();
//verify if shutwown is caused by an error
if (isset ($last_error['type']) && $last_error['type'] == E_ERROR)
{
/*
my activity for log or messaging
you can use info:
$last_error['type'], $last_error['message'],
$last_error['file'], $last_error['line']
see about on the manual PHP at error_get_last()
*/
}
}
register_shutdown_function ('shutDown_handler');
我在 PHP 7 中發現 try/catch 適用於“調用未定義函數”錯誤。 被捕獲的異常對象不是 Throwable 類,也不是 ErrorException 而是 Error。
catch 接收到的異常對象包含錯誤信息、文件和行號、堆棧跟蹤,但不包含嚴重性代碼。
此捕獲允許程序進行自己的日志記錄或分析,並從用戶可見的輸出中隱藏錯誤消息(但會將錯誤記錄在 PHP 錯誤日志中),這正是生產網站上需要的。 它還允許繼續執行,這可能很危險,但您可以簡單地放置“退出”; 在 catch 代碼塊的末尾,以防止程序繼續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.