如何避免'on a non-object in ***'错误



我正在使用simple_html_dom这样的

$html = new simple_html_dom();
$html->load_file($url);
$html->find('a')

然后有时会发生此错误

Fatal error: Call to a member function find() on a non-object in /src/Acme/TopBundle/Command/simple_html_dom.php on line 1146

还可以。我认为,LOAD_FILE无法获得URL的内容;

可能会发生。

但是,我想通过此错误并继续过程。

所以我更改了脚本。

$html = new simple_html_dom();
$html->load_file($url);
if (!$html){
            return null;
}
$html->find('a')

,但它仍然返回错误并停止。

如何通过此错误?

使用is_object:

$html = new simple_html_dom();
$html->load_file($url);
if (!is_object($html){
            return null;
}
$html->find('a')

您也可以进行定义的检查并使用getType。

<?php
require('simple_html_dom.php');
$html = new simple_html_dom();
$html->load_file('http://www.bensoft.com/');
if (defined($html) && gettype($html) == 'object') {
  $html->find('a');
}
?>

最新更新