Why is this class working?

I am trying to learn more about PHP’s DOM functions and about using classes.

The following test code echo’s the h1 tag’s attribute: “this is an attribute” as expected.

$html = '<h1 attribute="this is an attribute">H1 title</h1>';

$dom = new DOMDocument();


$xpath = new DOMXPath($dom);

$query = '//h1';

$node = $xpath->query($query);

foreach($node as $node)

		echo $node->getAttribute('attribute');



According to what I have read on php.net about classes they must be initialized before they are used or inherited from a parent class. Hence “$dom = new DOMDocument()” and “new DOMXPath($dom)” in the above test code.

What is confounding me is the “getAttribute()” method. According to php.net (http://us2.php.net/manual/en/class.domelement.php); the “getAttribute()” method is part of the DOMElement class.

I never initialed the DOMElement class by writing something like: “$var = new DOMElement()” yet I am still able to use the class’s method “getAttribute()”

How is this so?

$node is an instance of class that that has the method. The class was instantiated internally by the DOMXPath when calling query.

DOMXPath’s query method returns an object of type DOMNodeList (PHP handles creating this object for you) which you loop over. When looping, your $node is a DOMElement which has been created by PHP for you to use.

If you haven’t already, may I suggest a good read through of the Object-Oriented Programming section of the PHP manual.