Andreas Korthaus wrote:
Hi!
I've a question regarding the example in DOMElement::setAttribute()
chapter of the PHP manual: http://de3.php.net/dom-domelement-setattribute
There, an attribute is added to an element this way:
<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("root");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
echo $doc->saveXML();
?>
$doc->createElement() returns the created DOMElement,
$doc->appendChild() returns the appended DOMNode. Isn't this the same
object? Is it a reference?
I'm asking, because the following works too:
<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("root");
$node->setAttribute("align", "left");
$doc->appendChild($node);
echo $doc->saveXML();
?>
I like the 2nd example more, because first you create an object
(DOMElement), add some attributes to the object and after that append it
somewhere to the DOM tree. The 1st example creates a new DOMElement
object, appends it to the DOM tree, and adds the attributes not to the
created object, but to another object (the DOMNode appended to the
tree), which seems to be a reference to the original object.
Why does the manual prefer the (IMO less intuitive) 1st way? Is there a
problem with the 2nd way?
Both ways are perfectly valid. $node and $newnode refer to the same
object. It was written the 1st way to demonstrate the return value of
appendChild(), because in many cases people create the element differently.
i.e.
$newnode = $doc->appendChild($doc->createElement("root"));
or
$newnode = $doc->appendChild(new DOMElement("root"));
Also, in the event $node is created using the new DOMElement syntax:
$node = new DOMElement("root");
the node is read only and must be appended into the tree before it can
be modified, so the example just tries to be neutral here regarding the
syntax used.
Rob
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php