1
之間發生的事情與PHP類型轉換。當我這樣做:什麼是數組和對象
<?php
$object = array(
'key' => 'value',
1 => 'value',
'11' => 'value',
'22' => 'value'
);
print_r($object); echo'<br>';
$object = (object)$object;
print_r($object); echo'<br>';echo'<br>';
//ok looks good so far but then
echo $object->key . '<br>'; // good
echo $object->{1} . '<br>'; // bad
echo $object->{11} . '<br>'; // bad
echo $object->{'22'} . '<br>'; // bad
$object->key = 'changed value';
$object->{1} = 'changed value';
$object->{'11'} = 'changed value';
$object->{'22'} = 'changed value';
echo'<br>'; print_r($object); echo'<br>';echo'<br>';
echo $object->key . '<br>'; // good
echo $object->{1} . '<br>'; // good
echo $object->{11} . '<br>'; // good
echo $object->{'22'} . '<br>'; // good
$object = (array)$object;
echo'<br>'; print_r($object);echo'<br>';echo'<br>';
echo $object['key'] . '<br>'; // good
echo $object[1] . '<br>'; // wtf
echo $object['11'] . '<br>'; // wtf
echo $object['22'] . '<br>'; // wtf
?>
我得到這個的結果是:
Array ([key] => value [1] => value [11] => value [22] => value)
stdClass Object ([key] => value [1] => value [11] => value [22] => value)
value
Notice: Undefined property: stdClass::$1 in C:\Users\wl\Documents\USBWebserver v8.5\USBWebserver v8.5\8.5\root\Client\test.php on line 19
Notice: Undefined property: stdClass::$11 in C:\Users\wl\Documents\USBWebserver v8.5\USBWebserver v8.5\8.5\root\Client\test.php on line 20
Notice: Undefined property: stdClass::$22 in C:\Users\wl\Documents\USBWebserver v8.5\USBWebserver v8.5\8.5\root\Client\test.php on line 21
stdClass Object ([key] => changed value [1] => value [11] => value [22] => value [1] => changed value [11] => changed value [22] => changed value)
changed value
changed value
changed value
changed value
Array ([key] => changed value [1] => value [11] => value [22] => value [1] => changed value [11] => changed value [22] => changed value)
changed value
value
value
value
這是在PHP中的錯誤,爲什麼會出現這種情況。數組或對象如何具有2個具有不同值的相等鍵!?
其正確的是他將新的值添加到對象。 – Svetoslav
我沒有聲稱這是OOP,但很好。這個PHP行爲真的沒有被懷疑。爲什麼這不會產生致命的錯誤。數組如何仍然包含對象屬性。當然還有其他的方法。具有數組值的對象。它只是一個php wtf。 – botenvouwer
@sirwilliam跆拳道或不,看看這裏http://3v4l.org/V6lD1#v500,這是有道理的。沒有試圖得罪,對不起。 –