jcadima
7/5/2015 - 3:56 AM

How to access object properties with names like integeres

How to access object properties with names like integeres

<?php
http://stackoverflow.com/questions/10333016/how-to-access-object-properties-with-names-like-integers


// Fact #1: You cannot access properties with names that are not legal variable names easily
$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->123foo; // error


//Fact #2: You can access such properties with curly brace syntax
$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->{'123foo'}; // OK!


//Fact #3: But not if the property name is all digits!
$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->{'123foo'}; // OK!
echo $o->{'123'}; // error!


//Fact #4: Well, unless the object didn't come from an array in the first place.
$a = array('123' => '123');
$o1 = (object)$a;
$o2 = new stdClass;
$o2->{'123'} = '123'; // setting property is OK

echo $o1->{'123'}; // error!
echo $o2->{'123'}; // works... WTF?