I am trying to generate an xml file using the below class, when an array data is passed with no depth constraints the xml gets generated by the below code successfully. I am just trying to figure out as how self::createNode($value, $child); statements works does it create a new object? what is the significance of the the parent::_construct statement in the class constructor ? as the encoding is initialized already in the child class constructor.
What I have read since now about the self keyword is that it is used to call the static methods, but here the createNode method is non static. Will someone be able to help me out in understanding the context of this statement, what I can say here is the the DomDocument class doesn’t have any createNode method at all. Will anyone be able to help?
Thank you very much.
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();
}
}
In PHP
selfalways refers to the class whereselfwas executed. So in your caseselfwill refer to a method inside the classarray2xml.Usually
selfis used to callstaticmethods. Since in your case the method that is called byselfisn’t static, it would have been better to use$thisinstead.Where
parentalways calls the method from the “parent” class. So the class that is extended. Again in your case whenparent::some function()is called, it will search for that method in theDomDocumentclass. Because that is the “parent” (extended) class.The reason that
parent::__construct()is called in the constructor of thearray2xmlclass, is because the constructor of the extended class is never called automatically when your own class also uses a__construct(). Unless your class does not have a__construct(). Only then PHP will call the__construct()of the parent class. Otherwise you’ll have to call it manually from your own constructor.