【问题标题】:passing DOMDocument and DOMElement to PHP function将 DOMDocument 和 DOMElement 传递给 PHP 函数
【发布时间】:2021-11-23 14:09:23
【问题描述】:

我写了两个函数,用于在 PHP DOMDOcument 中按 className 查找元素

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

是否可以通过自动检测第一个参数是DOMDocument还是DOMElement来将这两个函数合并为一个?

【问题讨论】:

  • 为什么需要检测?两种情况下的代码都是一样的。

标签: php dom domdocument


【解决方案1】:

DOMDocumentDOMElement 都是 DOMNode 的子类,因此请使用该类型来包含两者。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-19
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多