数组和对象之间的PHP类型转换是怎么回事

时间:2013-10-17 13:25:34

标签: php arrays

当我这样做时:

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

1 个答案:

答案 0 :(得分:5)

<强>更新

NikiC为我提供了答案,这里有解释:The 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);

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