問題描述
在 PHP 中,有什么方法可以忽略未定義的函數,而不是拋出在瀏覽器中可見的致命錯誤?—即,致命錯誤:調用未定義的函數>
我知道有將所有自定義函數包裝在如下條件中的做法,但是有沒有一種編程方式來獲得這種效果?
if (function_exists('my_function')) {//在這里使用 my_function();}
沒有.致命錯誤是致命的.即使您要編寫自己的錯誤處理程序或使用 @
錯誤抑制運算符,E_FATAL
錯誤仍會導致腳本停止執行.
處理這個問題的唯一方法是使用 function_exists()
(可能還有 is_callable()
為很好的措施)如上面的例子.
圍繞潛在的(可能的?)錯誤進行防御性編碼總是比讓錯誤發生并在以后處理它更好的主意.
EDIT - php7 改變了這種行為,未定義的函數/方法是可捕獲的異常.
In PHP, is there any way that I can ignore functions that are undefined instead of throwing a fatal error that is visible in the browser?—i.e., Fatal error: Call to undefined function
I know that there is the practice of wrapping all custom functions in a conditional as below, but is there a programmatic way to get this effect?
if (function_exists('my_function')) {
// use my_function() here;
}
No. Fatal errors are fatal. Even if you were to write your own error handler or use the @
error suppression operator, E_FATAL
errors will still cause the script to halt execution.
The only way to handle this is to use function_exists()
(and possibly is_callable()
for good measure) as in your example above.
It's always a better idea to code defensively around a potential (probable?) error than it is to just let the error happen and deal with it later anyway.
EDIT - php7 has changed this behavior, and undefined functions/methods are catchable exceptions.
這篇關于在 PHP 中是否可以防止“致命錯誤:調用未定義的函數"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!