Search code examples
phpoopreflectionsimplexmldowncast

Cast Object to Subclass in PHP


I'm trying to extend the SimpleXMLElement class to provide a mechanism to merge sub XML string or other SimpleXMLElement into my SimpleXMLElement, code for that is based on code written by Carlos C Soto in an answer to the question "PHP - SimpleXML - AddChild with another SimpleXMLElement".

For now I'm adding only a addXml function in subclass (should work analog to the built in addChild by returning the newly created element) but I guess that every function call will return a SimpleXMLElement and not my newly created subclass. Is there a way to downcast in PHP comparable to Java?

edit as someone thought to downvote without any reason: I'm no Java Developer and normally I would't mind even with this kind of problem but SimpleXMLElement is a PHP class so I can't easily wrap it without writing lots of code. Maybe some kind of reflection magic making this possible?


Solution

  • When you extend from SimpleXMLElement the parent methods will give you your new type:

    class MyXml extends SimpleXMLElement
    {
    }
    
    $xml = new MyXml('<root />');
    
    $child = $xml->addChild('child');
    
    var_dump(get_class($child)); # string(5) "MyXml"
    

    This is specific to SimpleXMLElement and not PHP in general. So you would always have to try. This is what the person who commented on your question was trying to tell you.

    Next to that, the simplexml_import_dom function has a second parameter for which you can name the class-name. You can also pass a SimpleXMLElement object for it as well, PHP will then take the class-name from the instance.