开发者

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

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?


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜