9

This is... I don't even know what this is happening.

// var_dump of items before
object(stdClass)[84]
   public '75' => object(stdClass)[87]

$items = (array) $items; // Casting unserialized stdClass to array
var_dump($items);

//Result of var dump:
array
  '75' => 
    object(stdClass)[87]

//Now lets get this item:
var_dump($items[75]); // Error
var_dump($items['75']); // Error

What the?

Thanks.

3
  • Try to cast into a different variable $new_items = (array) $items; var_dump($new_items[75]); Commented May 25, 2012 at 17:05
  • This gives me the same result. Commented May 25, 2012 at 17:08
  • Reproducible Example Commented May 25, 2012 at 17:19

2 Answers 2

3

I think, you are using a debug extension, so the var_dump() output is different then standart library, properties can not be numeric but $obj->{'75'} is okay. If can you reach to the sub object by $items->{'75'} yes you have a numeric property. otherwise you can try print_r($items); and see the original output, or check the array after get_object_vars()

    <?php

$items = new stdClass();
$items->{'75'} = new stdClass();
$items->{'75'}->{'85'} = new stdClass();


$items = (array) $items; // Casting unserialized stdClass to array
$items_array = get_object_vars($items); // getting object vars as an array.

var_dump($items["75"]); // Error
var_dump($items['75']); // Error
var_dump($items_array['75']); // Works

PHP issue : #45959

Read the casting blockquote: http://www.php.net/manual/en/language.types.array.php#language.types.array.casting

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, when $items is still an object I CAN reach the "75" with $obj->{'75'}. Please, look: pastebin.com/nTbGscD5
so, you have to use get_object_vars();
It worked, thanks. It was weird, because I've used array_keys on the $items after casting it to array and it worked.
+1 Awesome research @TufanBarışYıldırım - Thanks for digging up that tidbit about casting objects to arrays. Explains everything nicely.
2

Casting to an array doesn't work like that.

See here: get_object_vars() vs. cast to array

and here: http://www.php.net/manual/en/language.types.array.php#language.types.array.casting

Blockquote "If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.