Search code examples
phpdomdomdocument

passing DOMDocument and DOMElement to PHP function


I wrote two functions for finding elements by className in PHP DOMDOcument

function byClass(DOMDocument $a,$b,$c){
    foreach($a->getElementsByTagName($b) as $e){
        if($e->getAttribute('class')==$c){$r[]=$e;}
    }
return $r;
}

function byClass2(DOMElement $a,$b,$c){
    foreach($a->getElementsByTagName($b) as $e){
        if($e->getAttribute('class')==$c){$r[]=$e;}
    }
return $r;
}

Is it possible to merge these two functions into one by auto-detecting if the first argument is DOMDocument or DOMElement?


Solution

  • DOMDocument and DOMElement are both subclasses of DOMNode, so use that type to encompass both.

    function byClass(DOMNode $a,$b,$c){
        foreach($a->getElementsByTagName($b) as $e){
            if($e->getAttribute('class')==$c){$r[]=$e;}
        }
        return $r;
    }