简而言之我的问题是"我想创建一个语言系统,我想访问像$language->fields->username->admin
这样的短语,所以我尝试以不同的方式做到这一点,但我无法将数组合并到对象,我的意思是想要将数组转换为对象并添加将返回语言对象的对象。
class Language
{
public function __construct(array $array)
{
$this += (object) $array;
}
}
答案 0 :(得分:1)
您无法通过简单的操作员执行此操作。您需要遍历数组以分配属性。
function makeObjectRecursively($array) {
if (!is_array($array)) {
return $array;
}
foreach ($array as $k => &$v) {
$v = makeObjectRecursively($v);
}
return (object) $array;
}
foreach ($array as $k => $v) {
$this->$k = makeObjectRecursively($v);
}
答案 1 :(得分:0)
您所描述的内容听起来有点像RecursiveArrayObject
:
class Language extends RecursiveArrayObject
{
public function __construct(array $array)
{
parent::__construct($array, ArrayObject::ARRAY_AS_PROPS);
}
}
$data = ['fields' => ['username' => ['admin' => 'ADMINv']]];
$language = new Language($data);
echo $language->fields->username->admin, "\n"; # prints "ADMINv"
RecursiveArrayObject
是ArrayObject
的一个更具体的形式:
class RecursiveArrayObject extends ArrayObject
{
public function __construct(Array $array, $flags = 0, $iterator_class = "ArrayIterator")
{
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = new static($value, $flags, $iterator_class);
}
$this->offsetSet($key, $value);
}
$this->setFlags($flags);
$this->setIteratorClass($iterator_class);
}
}