\stdClass
doesn't have a constructor that accepts an array as an argument. You can add the array explicitly as a property. Try:
function arrayToObject(array $array, $property = 'myArrayProperty')
{
$test = new \StdClass($array);
$test->{$property} = $array;
return $test;
}
$arr = ['foo' => 1, 'bar' => 2];
$obj = arrayToObject($arr);
// `echo $obj->myArrayProperty['foo']` => 1
print_r($obj)
This yields:
stdClass Object
(
[myArrayProperty] => Array
(
[foo] => 1
[bar] => 2
)
)
Unless you want to actually convert the array into an object, (which is more useful in my view) where the array keys become the object properties. In which case you can perform a direct cast:
$arr = [
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
];
$obj = (object) $arr;
print_r($obj);
Yields:
stdClass Object
(
[key1] => value1
[key2] => value2
[key3] => value2
)
Access via:
echo $obj->key1; // 'value1'
Hope this helps :)
EDIT
I had a closer look at the example output you want. You want to create a \stdClass
object, with a test
property. This is an array containing one element: a nested \stdClass
object containing properties and values from the array.
Are you looking for something like this?
$arr = [
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
];
$obj = new \stdClass();
$obj->test = [(object) $arr];
var_dump($obj);
Yields:
class stdClass#1 (1) {
public $test =>
array(1) {
[0] =>
class stdClass#2 (3) {
public $key1 =>
string(6) "value1"
public $key2 =>
string(6) "value2"
public $key3 =>
string(6) "value3"
}
}
}