1

当我这样做时:

<?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 个不同值的相等键!?

4

1 回答 1

5

更新:

NikiC给了我一个答案,这里有解释:Symtable

基本上,数组将数字键存储为整数,对象将数字键存储为字符串。但是,当您执行数组到对象或对象到数组的强制转换时,不会强制执行该约束。

array (size=7)
  'key' => string 'changed value' (length=13)
  1 => string 'value' (length=5)
  11 => string 'value' (length=5)
  22 => string 'value' (length=5)
  '1' => string 'changed value' (length=13)
  '11' => string 'changed value' (length=13)
  '22' => string 'changed value' (length=13)

这是不正确的;例如,11 是整数,'11' 是字符串(两个不同的键)。

使用var_dump而不是print_r,因为它显示类型。

我建议你试试这个脚本:

<?php

$object = array(
  'key' => 'value',
  1 => 'value',
  '11' => 'value',
  '22' => 'value'
);

$object = (object) $object;

var_dump($object);

$object->key = 'changed value';
$object->{1} = 'changed value';
$object->{'11'} = 'changed value';
$object->{'22'} = 'changed value';

$object = (array) $object;

var_dump($object);

这里肯定有一些奇怪的地方,但你不能指望得到好的结果,因为以整数开头的变量是非法的。

于 2013-10-17T13:30:33.397 回答