0

When I run this bit

$data = (object)array(1,2,3);
print_r($data);

I get

stdClass Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)

This is rather interesting because I've known up until now that an object's property name cannot start with a number. So if that is true it must mean that these values are not properties, but what are they then?

A few ways I tried to access the values

$data[0]; // Fatal error:  Cannot use object of type stdClass as array
$data->0; // Parse error:  syntax error, unexpected 0, expecting identifier
$data->{0}; // Notice:  Undefined property: stdClass::$0

I'm not really interested in accessing the values rather than finding out how they are kept in the class if they're not properties and not indexed values.

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
  • 3
    possible duplicate of [How to access object properties with names like integers?](http://stackoverflow.com/questions/10333016/how-to-access-object-properties-with-names-like-integers) – sybear Oct 10 '14 at 11:46

3 Answers3

1

That's not possible right now I think, you need some trick to solve that. Probably following technique

<?php

$data = (object)array(1,2,3);
$newData = array();
foreach($data as $k=>$v){
    print "key: $k, value: $v<br />";
    $newData[$k] = $v;
}

print $newData[0];

I'm not sure about your situation. If you explain few line, that'll be helpful

Sabbir
  • 1,374
  • 1
  • 15
  • 23
0

You can't access simply because a variable (attribut in class) name can't start with a number. So it's why ->0 is error.

If you want to use [] to access attributes of a class, you have to implement the interface ArrayAccess : http://php.net/manual/fr/class.arrayaccess.php

After implemented, you'll be able to access to $data[0] :)

David Ansermot
  • 6,052
  • 8
  • 47
  • 82
0

I'm not really interested in accessing the values rather than finding out how they are kept in the class if they're not properties and not indexed values.

That means diving into PHP´s internals, which is probaly not where you want to find yourself. You'd have to check PHP's own source code to see what exactly is happening in these cases.

Is there a specific reason you want to know?

Erik
  • 1,057
  • 7
  • 11