Googlebot
Googlebot

Reputation: 15683

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?

Upvotes: 0

Views: 160

Answers (1)

Barmar
Barmar

Reputation: 781731

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

Upvotes: 3

Related Questions