2011-12-13 140 views
0
class MyClass { 

    public function __construct(){ 
    } 

    private function makeError(){ 
     return sp('ABC'); // sp is undefined function 
    } 

    private function printMe(){ 
     echo "PRINT ME"; 
    } 

    public function run(){ 

     try { 
      $t = $this->makeError(); 

     }catch(Exception $e){ 
     } 

     $this->printMe();  
    } 
} 

$t = new MyClass(); 
$t->run(); 

如果運行上面的代碼,會發生錯誤,因爲sp()未定義函數。PHP忽略錯誤並繼續處理

但我想忽略錯誤並運行printMe方法。

我該怎麼辦?

謝謝!

+0

這是否拋出什麼類型的錯誤? – 2011-12-13 17:03:00

回答

1

你可以使用function_exist()

class MyClass { 

    public function __construct(){ 
    } 

    private function makeError(){ 
     if(!function_exist('sp')){ 
      throw new Exception(); 
     }else{ 
      return sp('ABC'); // sp is undefined function 
     } 
    } 

    private function printMe(){ 
     echo "PRINT ME"; 
    } 

    public function run(){ 

     try { 
      $t = $this->makeError(); 

     }catch(Exception $e){ 
     } 

     $this->printMe();  
    } 
} 

你追不上它does'n存在的事實,因爲這是一個致命的錯誤

0

這是不可能的。這是一個致命的錯誤,不是一個例外。
因此它不能被捕捉。

在這種非常情況下,你可以避開與導致錯誤但是:

if (function_exists("sp")) { 
    return sp('ABC'); // sp is undefined function 
} 

同樣,你可以換你的電話$this->makeError();與測試。但這意味着要處理另一種內部方法。無論如何,這隻會避免那種超級特定的邊緣情況。