简体   繁体   English

PHP调用未定义的方法DOMElement

[英]PHP Call to undefined method DOMElement

I have wrap class for creating xml file and i dont know how to rewrite add() method to work correctly. 我有用于创建xml文件的包装类,但我不知道如何重写add()方法以使其正常工作。 Variable SHOPITEM should be parent element, but i dont know how to reach it in add method. 变量SHOPITEM应该是父元素,但是我不知道如何在add方法中达到它。

Any advice are welcome 欢迎任何建议

  class Items {

    const XML_VERSION enter code here= '1.0';
    const XML_ENCODING = 'utf-8';
    const SHOP = 'SHOP';

    private $xml, $xmlElement;

    public function __construct() {
        $this->xml = new DOMDocument(self::XML_VERSION, self::XML_ENCODING);
        //$this->xml->preserveWhiteSpace = false;
        $this->xml->formatOutput = true;
        $this->xmlElement = $this->create(self::SHOP);
    }

    public function create($nodeName, $value = null) {
        return $this->xml->createElement($nodeName, $value);
    }

    public function add($object) {
        return $this->xmlElement->appendChild($object);
    }

    public function write() {
        $this->xml->appendChild($this->xmlElement);
        $this->xml->save("test.xml");
    }

}

$items = new Items();
$SHOPITEM = $items->create('SHOPITEM');
$product1 = $items->create('Product1', 'Some value 1');
$product2 = $items->create('Product2', 'Some value 2');

//this wont work
$SHOPITEM->add($product1);

//this works
$items->add($product1);
$items->add($product2);

//this works
$items->add($SHOPITEM);

$items->write();

Your $SHOPITEM , $product1 and $product2 are instances of newly added node (ie of DOMElement class) because they are result of the statement $SHOPITEM$product1$product2是新增加节点的情况下(即一个DOMElement类的),因为它们是语句的结果

return $this->xml->createElement($nodeName, $value);

So they just do nat have a method add($object) that you want to use on them. 因此,它们只是没有要在其上使用的方法add($object)

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

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