爲什麼(array)不工作?因爲DOMNodeList對象只有一個屬性,length,它是整數類型:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.
由於DOMNodeList實現Traversable接口,這是相當容易地創建自己的數組:
$array = array();
foreach($names as $node){
$array[] = $node;
}
編輯:我刪除了最初的解釋,因爲它不適用於此。什麼是人工的手段是用數字名稱屬性傳遞到數組,但不能讀:
<?php
class Foo{
public function __construct(){
$this->{123} = 456;
}
}
$array = (array)new Foo;
var_dump($array);
var_dump($array['123']);
array(1) {
["123"]=>
int(456)
}
Notice: Undefined offset: 123 in D:\tmp\borrame.php on line 11
NULL
的解釋可能更上線即DOMNodeList
不與PHP代碼創建了一個用戶對象,但C中定義的內置對象,因此適用不同的規則。
這應該是正確的答案。它的工作原理非常簡單。 – 2014-08-27 12:32:25
同意。這是最好的。 – 2015-04-10 19:36:45
這不適合我。 '可捕獲的致命錯誤:傳遞給iterator_to_array()的參數1必須實現接口Traversable,DOMNodeList的實例給定' – 2015-05-26 20:34:27