普通网友 2016-04-17 04:02
浏览 44

一步分配xpath-> query和read length

Why is this not allowed? (I get a syntax error at the ->length):

($x=$xpath->query($s))->length

According to the http://php.net/manual/en/language.operators.assignment.php the value of an assignment expression is the value assigned, but it does not seem to work when assigning the result of a xpath->query.

I want to use the expression in a while loop, where I'm assigning the query result and checking for zero-length in one step:

// $xpath is a DOMXPATH object
while(($x=$xpath->query($s))->length){
    // do something with $x
}
  • 写回答

1条回答 默认 最新

  • dougang7521 2016-04-17 08:15
    关注

    I'm not in anyway a PHP expert, but from what I observed, it is combination of the parentheses and object operator (->) that triggers the error. The assignment expression itself correctly returns an instance of DOMNodeList, as we expect given the linked documentation :

    $xml = "<person><name>John-Doe</name></person>";
    $doc = new DOMDocument();
    $doc->loadXML($xml);
    $xpath = new DOMXpath($doc);
    
    $test = ($x = $xpath->query("/person/foo"));
    //$test contains instance of `DOMNodeList` on which we can use `->` to get the length
    echo $test->length;
    
    //but using `->` on parentheses triggers the initial error :
    echo ($test)->length;
    

    To achieve the actual goal, you maybe able to use plain for loop, which provides more flexibility in controlling the loop, instead of using while. Something along the lines of the following snippet :

    for($x=$xpath->query($s);
        $x->length;
        $x=$xpath->query($s))
    {
        //do something with $x
    }
    

    I assume that $xpath->query($s) result changes in the next iterations, in a way that $x->length value decreases, so that the loop will eventually terminates.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度