繁体   English   中英

在另一个类中使用php dom解析器 - 错误:调用非对象上的成员函数

[英]use php dom parser inside another class - ERROR: Call to a member function on a non-object

我正在使用PHP简单的dom解析器http://simplehtmldom.sourceforge.net/manual.htm 我能够成功地使用它并通过执行删除具有特定id的html标记

$html = str_get_html('<div><div class="two">two</div></div>');     
function test($str, $class){
    $e = $str->find($class,0);
    $e->outertext = '';
    echo $str->outertext;
}
test($html, '#two'); 

我的问题是当我尝试在另一个php类中使用该函数时。 它不起作用。 这就是我所做的

$html = new simple_html_dom(); //initialized the object

class Someclass {
    public function test($wrap, $class){
        global $html;
        $html->load($wrap);
        $e = $html->find($class,0);
        $e->outertext = '';
        echo $html->outertext;
    }    
}

我收到错误致命错误:在非对象上调用成员函数load()我做错了什么。 我正确地说这个。

您可以在函数内创建html dom解析器的新实例:

// include dom parser file first
class Someclass {
    public function test($wrap, $class){
        $html = new simple_html_dom(); //initialized the object
        $html->load($wrap);
        $e = $html->find($class,0);
        $e->outertext = '';
        echo $html->outertext;
    }    
}

还要确保使用includerequire在上面的类中包含了html解析器类。

顺便说一句,如果要在类的各种函数中使用dom解析器,则应在构造类时创建类级变量并存储它的新实例,如下所示:

// include dom parser file first
class Someclass {
    protected $html_parser = null;

    public function __construct(){
        $this->html_parser = new simple_html_dom();
    }    
}

现在,您将可以在类的不同功能中使用$this->html_parser

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM