0

I need to know is there a way to create an object with properties with number instead of names in php, so I can get them like this:

$property = $obj->{1}
Sargis
  • 168
  • 4
  • 12
  • Have you seen https://stackoverflow.com/questions/17159295/accessing-object-with-key-as-number-php – user3783243 Aug 23 '19 at 14:00
  • I think you can try this by making your class implement ArrayAccess. Never tried it though. But honestly speaking, just don't do this. Object properties need to be descriptive. Having them as numbers doesn't mean anything. – nice_dev Aug 23 '19 at 14:11
  • Are you, perhaps, working with a JSON and want to retrieve data based on its index? For example - https://stackoverflow.com/questions/9606340/get-a-php-object-property-that-is-a-number – waterloomatt Aug 23 '19 at 14:31
  • Also see this - https://stackoverflow.com/q/10333016/296555 – waterloomatt Aug 23 '19 at 14:33
  • maybe is my preference, but I find it much better to go for named properties. Makes the usage clearer and more readable. – treyBake Aug 23 '19 at 19:55

2 Answers2

1

Er... Yes, you can. It's the very same syntax you are already using:

$obj = (object)nuLL;
$obj->{1} = 'Hi!';
var_dump($obj);

(Demo)

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

U can't set name property of object as integer . If you want iterate properties

get_object_vars($object);

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28