6

I have a stdClass Object like this:

print_r($myobj);

stdClass Object(
[0] => testData
);

So it is clear that I cannot get the value by $myobj->0.

For getting this value I convert the object to an array, but are there any ways to get without converting?

Will
  • 24,082
  • 14
  • 97
  • 108
sinitram
  • 524
  • 5
  • 14

2 Answers2

6

Try this:

$obj = new stdClass();

$obj->{0} = 1;

echo $obj->{0};

source: http://php.net/manual/en/language.types.object.php

narasimharaosp
  • 533
  • 3
  • 12
0

So firstly, even though it appears from print_r()'s output that the property is literally integer 0, it is not. If you call var_dump() on the object instead, you'll see that, in fact, it looks like this:

php > var_dump($myobject);
object(stdClass)#2 (1) {
  ["0"]=>
  string(4) "testData"
}

So how do you access a property named 0 when PHP won't let you access $myobject->0? Use the special Complex (curly) syntax:

php > echo $myobject->{0};
test
php > echo $myobject->{'0'};
test
php >

You can use this method to access property names that are not considered valid syntax.

Will
  • 24,082
  • 14
  • 97
  • 108