----- Original Message -----
From: "Rob" <rrichards@xxxxxxxxxxxxxxxx>
To: "Andreas Korthaus" <akorthaus@xxxxxx>
Cc: <php-general@xxxxxxxxxxxxx>
Sent: Friday, March 03, 2006 4:43 PM
Subject: Re: DOMElement::setAttribute() manual example question
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?
Check out:
http://de3.php.net/manual/en/function.dom-domdocument-createelement.php
( This function creates a new instance of class DOMElement. This node will
not show up in the document unless it is inserted with e.g.
DOMNode->appendChild().)
I really don't understand WHY your next example is working...
/G
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
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php