0

我正在尝试使用下面的类生成一个 xml 文件,当传递一个没有深度约束的数组数据时,下面的代码会成功生成 xml。我只是想弄清楚 self::createNode($value, $child);语句是如何工作的,它会创建一个新对象吗?parent::_construct类构造函数中的语句有什么意义?因为编码已经在子类构造函数中初始化。从现在开始,我所读到的关于 self 关键字的内容是它用于调用静态方法,但这里的 createNode 方法是非静态的。有人能帮我理解这句话的上下文吗,我在这里可以说的是 DomDocument 类根本没有任何 createNode 方法。有人能帮忙吗?非常感谢你。

class array2xml extends DomDocument
{
    public $nodeName;
    private $xpath;
    private $root;
    private $node_name;
    public $xml_data;

    public function __construct($root='root', $node_name='node')
    {
        parent::__construct();
        $this->encoding = "UTF-8";
        $this->formatOutput = true;
        $this->node_name = $node_name;
        $this->root = $this->appendChild($this->createElement($root));
        $this->xpath = new DomXPath($this);
    } 

    public function createNode( $arr, $node = null)
    {   
        if (is_null($node))
        {
            $node = $this->root;
        }
        foreach($arr as $element => $value) 
        {
            $element = is_numeric( $element ) 
                ? $this->node_name 
                : $element;
            $element = htmlspecialchars($element,ENT_QUOTES,'UTF-8');
            $child = $this->createElement($element, (is_array($value) 
                ? null 
                : htmlspecialchars($value,ENT_QUOTES,'UTF-8')));
            $node->appendChild($child);
            if (is_array($value))
            {
                self::createNode($value, $child);
            }
        }
    }

    public function __toString()
    {
        $this->xml_data= $this->saveXML();
        return $this->saveXML();
    }
}
4

1 回答 1

1

在 PHP中self 总是self被执行的类。因此,在您的情况下,self将引用类中的方法array2xml

通常self用于调用static方法。由于在您的情况下调用的方法self不是静态的,因此最好使用它$this

whereparent总是从“父”类调用方法。所以扩展的类。同样在您的情况下,当parent::some function()被调用时,它将在DomDocument类中搜索该方法。因为那是“父”(扩展)类。

在类parent::__construct()的构造函数中调用的原因是,当您自己的类使用. 除非你的班级没有. 只有这样 PHP 才会调用父类的。否则,您将不得不从您自己的构造函数中手动调用它。array2xml__construct()__construct()__construct()

于 2013-01-02T10:18:34.173 回答