初始化对象像PHP中的数组? [英] Initialize Objects like arrays in PHP?
问题描述
在PHP中,您可以使用以下符号快速初始化带有值的数组:
In PHP, you can initialize arrays with values quickly using the following notation:
$array = array("name" => "member 1", array("name" => "member 1.1") ) ....
有什么方法可以对STDClass对象执行此操作吗? 我不知道比沉闷更短的方法
is there any way to do this for STDClass objects? I don't know any shorter way than the dreary
$object = new STDClass();
$object->member1 = "hello, I'm 1";
$object->member1->member1 = "hello, I'm 1.1";
$object->member2 = "hello, I'm 2";
推荐答案
From a (now dead) post showing both type casting and using a recursive function to convert single and multi-dimensional arrays to a standard object:
<?php
function arrayToObject($array) {
if (!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
本质上,您构造了一个接受$array
并对其所有键和值进行迭代的函数.它使用键将值分配给类属性.
Essentially you construct a function that accepts an $array
and iterates over all its keys and values. It assigns the values to class properties using the keys.
如果值是数组,则可以再次(递归)调用该函数,并将其输出分配为该值.
If a value is an array, you call the function again (recursively), and assign its output as the value.
上面的示例函数正是这样做的;但是,逻辑顺序可能与您自然地考虑该过程的顺序有所不同.
The example function above does exactly that; however, the logic is probably ordered a bit differently than you'd naturally think about the process.
这篇关于初始化对象像PHP中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!