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() 未定义函数。
但我想忽略错误并运行 printMe 方法。
我应该怎么做?
谢谢!
最佳答案
你可以使用 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();
}
}
你无法捕捉到它不存在的事实,因为这是一个 fatal error
关于PHP 忽略错误并继续处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8493051/