如何避免'在***中的非对象'错误

时间:2014-02-02 08:40:33

标签: php

我正在使用像这样的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')

但它仍会返回错误并停止。

我该如何传递抛出此错误?

2 个答案:

答案 0 :(得分:1)

使用is_object

$html = new \simple_html_dom();
$html->load_file($url);

if (!is_object($html){
            return null;
}
$html->find('a')

答案 1 :(得分:0)

您也可以进行定义检查并使用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');
}
?>