Home > Net >  passing DOMDocument and DOMElement to PHP function
passing DOMDocument and DOMElement to PHP function

Time:10-02

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?

CodePudding user response:

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;
}
  • Related