我正在尝试使用下面的类生成一个 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();
}
}