[英]Assign xpath->query and read length in one step
為什么不允許這樣做? (我在->length
處遇到語法錯誤):
($x=$xpath->query($s))->length
根據http://php.net/manual/zh/language.operators.assignment.php ,賦值表達式的值是已賦值,但是在分配xpath-> query的結果時似乎不起作用。
我想在while循環中使用該表達式,在其中分配查詢結果並一步檢查零長度:
// $xpath is a DOMXPATH object
while(($x=$xpath->query($s))->length){
// do something with $x
}
無論如何,我都不是PHP專家,但是從我觀察到的結果來看,觸發錯誤的是括號和對象運算符 ( ->
)的組合。 賦值表達式本身可以正確返回DOMNodeList
的實例,正如我們所期望的那樣,鏈接文檔如下:
$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;
為了實現實際目標,您也許可以使用普通的for
循環,而不是使用while
,它為控制循環提供了更大的靈活性。 以下代碼段中的內容:
for($x=$xpath->query($s);
$x->length;
$x=$xpath->query($s))
{
//do something with $x
}
我假設$xpath->query($s)
結果在下一次迭代中發生變化,其方式是$x->length
值減小,從而循環最終終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.