如何访问以下属性?

If I want to cast an index array to an object, is there a way to access the properties (with the -> operator) that were created in according to the array elements?

<?php
$numeric_index_array = array(10, 20, 30) ;

$obj_numeric_index = (object)$numeric_index_array ;

var_dump($obj_numeric_index) ;

You cannot access field if there is only digits. When you cast an object to a simple one dimensional array, fields are numbers.

array(10, 20, 30); // same as: array(0 => 10, 1 => 20, 2 => 30);

The only way is to create a two dimensional array with some chars. Example :

<?php
$numeric_index_array = array('1.' => 10, 2 => 20, '3' => 30) ;

$obj_numeric_index = (object)$numeric_index_array ;

var_dump($obj_numeric_index);

echo $obj_numeric_index->1.;      // no
echo $obj_numeric_index->'1.';    // no
echo $obj_numeric_index->{'1.'};  // OK !
echo $obj_numeric_index->2.;      // no
echo $obj_numeric_index->'2';     // no
echo $obj_numeric_index->{'2'};   // no
echo $obj_numeric_index->3;       // no
echo $obj_numeric_index->{3};     // no
echo $obj_numeric_index->{'3'};   // no

Not very practical, I agree.


Edit. Transform an array to an object, the right way:

<?php
$numeric_index_array = array(10, 20, 30) ;

$obj = new StdClass;
array_walk($numeric_index_array, function(&$val, $key) use (&$obj) {
    $obj->{$key} = $val;
});

echo $obj->{1}; // OK !