当PHP程序执行报错的时候,如何让剩下的代码继续执行?
程序员文章站
2022-04-15 20:48:06
...
比如下面的这段代码,打印的结果只显示public,然后报致命错,那么入伙跳过这段错误让后边的程序继续执行呢?想要的输出格式是
public
错误
错误
public protected private
class MyCLass
{
public $public='Public';
protected $protected='Protected';
private $private='Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
};
$obj=new MyCLass();
echo $obj->public;
echo $obj->protected;
echo $obj->private;
$obj->printHello();
public
错误
错误
public protected private
class MyCLass
{
public $public='Public';
protected $protected='Protected';
private $private='Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
};
$obj=new MyCLass();
echo $obj->public;
echo $obj->protected;
echo $obj->private;
$obj->printHello();
回复讨论(解决方案)
try catch捕捉处理下
是这样吗?但是还是第二行报错,后边的代码还是不会执行啊
try {
echo $obj->protected;
} catch (EmptyIterator $e) {
print $e->getMessage();
}
Cannot access protected property MyCLass::$protected
无法访问受保护的资源
这是致命性错误,不可回避!
换句话说:是你不懂规矩了
你可以用简单的调试函数来观察对象的属性
print_r($obj);
或
var_dump($obj);
致命错误是没办法跳过的,一旦发生,就会停止运行。
受教了,谢谢各位