Search code examples
phpmethodsdomdocumentchaining

Calling a different process when method chaining in PHP?


Firstly, sorry for my flawed english and being dumb :O

I just want to know any procedure to make this possible in method chaining. As per the DOMDocument class, the sequence of the characters are altered accordingly if we perform method chaining for example:

$dom = new DOMDocument();

$applicant = $dom->createElement('applicant');

$name = $dom->createElement('name');
$firstname = $dom->createElement('firstname', 'Joe');
$middlename = $dom->createElement('middlename', 'Johnson');
$lastname = $dom->createElement('lastname', 'Smith'); 

$dom->appendChild($applicant);
$applicant->appendChild($name);
    $name->appendChild($firstname);
    $name->appendChild($middlename);
$name->appendChild($lastname);

//OUTPUT

<applicant>
   <name>
      <firstname>Joe</firstname>
      <middlename>Johnson</middlename>
      <lastname>Smith</lastname>
   </name>
</applicant>

If I do

$dom->appendChild($applicant);
$applicant->appendChild($name);
        $name->appendChild($firstname)
             ->appendChild($middlename);
$name->appendChild($lastname);

//OUTPUT

<applicant>
   <name>
      <firstname>
           Joe
           <middlename>Johnson</middlename>
      </firstname>
           <lastname>Smith</lastname>
   </name>
</applicant>

-- How is that?


Solution

  • appendChild returns the appended child, so your next appendChild acts on that return value.

    So in your first example you're allways working on $name in the second twice on $name and once on $firstname.

    See: http://www.php.net/manual/en/domnode.appendchild.php