PHP SimpleXML未定义成员错误



我不明白为什么这是一个错误。一切对我来说都有意义。$logFileSimpleXMLElement,因此它们应该能够使用getName()方法。

错误:

致命错误:在C:xampphtdocsobjLogParser.php第29行中调用非对象的成员函数getName()

我已经在我的代码中标记了错误。

<?php
class objLogParser
{
    private $fileName;
    private $logFile;
    //Constructor
    public function __construct($varFileName)
    {
        $this->fileName = $varFileName;
        //Load as string
        $xmlstr = file_get_contents($varFileName);
        $logFile = new SimpleXMLElement($xmlstr);
        //Load as file
        $logFile = new SimpleXMLElement($varFileName,null,true);
    }
    public function printNodes()
    {
        $this->printHelper($this->logFile,0);
    }

    public function printHelper($currentNode, $offset)
    {
        echo $this->offset($offset);
        echo $currentNode->getName();  ////////////////////LINE 29 ERROR
        if($currentNode->attributes()->count() > 0)
            echo "({$currentNode->attributes()})";
        echo " {$currentNode}"; 
        foreach ($currentNode->children() as $child) {
            echo "<br>";
            printHelper($child, ($offset+1));
        }
    }
    function offset($offset)
    {
        for ($i = 0; $i < $offset; $i++)
            echo "_ ";
    }

}
?>

应该是$this->logFile->getName();。实质上,将$logFile替换为logFile

$this->logFile从未被设置。$logFile在__construct()中设置,但从未实际使用。$this->logFile和$logFile不是同一个变量。$logFile仅限于__construct()的作用域;你不能在那个方法之外访问它。$this->logFile可以被类中的任何方法访问。尝试将__construct()中的$logFile更改为$this->logFile.

最新更新