PHP: cast to (array) and return-type: array is not the same?

試著忘記壹切 提交于 2020-01-02 06:18:07

问题


I have following problem in PHP:

print_r() says it's the same, gettype() says same type, but the last output works not for both cases although they should be the same!

This looks very strange to me.

code and output:

$docdatau = get_object_vars(json_decode($docdata));
$docdatau2 = (array)json_decode($docdata);

echo "1\n";
echo gettype($docdatau);
echo "\n";
echo "--------------------------------------\n";
print_r($docdatau);
echo "--------------------------------------\n";

echo "2\n";
echo gettype($docdatau2);
echo "\n";
echo "--------------------------------------\n";
print_r($docdatau2);

echo "out1\n";
echo "--------------------------------------\n";
print_r($docdatau[0]);
echo "out2\n";
echo "--------------------------------------\n";
print_r($docdatau2[0]);

The output:

1
array
--------------------------------------
Array
(

    [0] => stdClass Object
        (
            [produkt] => Produkt 2
            [laufzeit] => 24
            [addtext] => sdsd
            [provision] => 39
        )

    [1] => stdClass Object
        (
            [produkt] => Produkt 1
            [laufzeit] => 
            [addtext] => 
            [provision] => 0
        )

)
--------------------------------------
2
array
--------------------------------------

Array
(

    [0] => stdClass Object
        (
            [produkt] => Produkt 2
            [laufzeit] => 24
            [addtext] => sdsd
            [provision] => 39
        )

    [1] => stdClass Object
        (
            [produkt] => Produkt 1
            [laufzeit] => 
            [addtext] => 
            [provision] => 0
        )

)
out1
--------------------------------------
stdClass Object
(
    [produkt] => Produkt 2
    [laufzeit] => 24
    [addtext] => sdsd
    [provision] => 39
)
out2
--------------------------------------
--------------------------------------

out1 and out2 should produce the same results but don't.

Perhaps anybody has a hint for me?


回答1:


There are several PHP bugs about it:

  • http://bugs.php.net/bug.php?id=45346
  • http://bugs.php.net/bug.php?id=51635
  • http://bugs.php.net/bug.php?id=46758

The same things happens here:

$obj->{0} = "hello";
$arr = (array)$obj;
echo $arr[0];

It happens because the "0" is used as string array key, whereas $arr[0] searches for the integer array key. It is documented in the PHP documentation simply by stating: integer properties are unaccessible (link).



来源:https://stackoverflow.com/questions/3527872/php-cast-to-array-and-return-type-array-is-not-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!