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