我一直在寻找一种方法来实现 ArrayObject 类来存储应用程序配置,我在 php 手册中找到了这个实现(其中一条评论)
<?php
use \ArrayObject;
/**
* Singleton With Configuration Info
*/
class Config extends ArrayObject
{
/**
*
* Overwrites the ArrayObject Constructor for
* Iteration throught the "Array". When the item
* is an array, it creates another static() instead of an array
*/
public function __construct(Array $array)
{
$this->setFlags(ArrayObject::ARRAY_AS_PROPS);
foreach($array as $key => $value)
{
if(is_array($value))
{
$value = new static($value);
}
$this->offsetSet($key, $value);
}
}
public function __get($key)
{
return $this->offsetGet($key);
}
public function __set($key, $value)
{
$this->offsetSet($key, $value);
}
/**
* Returns Array when printed (like "echo array();")
* Instead of an Error
*/
public function __ToString()
{
return 'Array';
}
}
用法:
$config = new Config\Config($settings);
$config->uri = 'localhost'; // works
$config->url->uri = 'localhost'; // doesn't work
print_r($config);
我已经尝试将 __get 和 __set 添加到此类中,它适用于简单的数组,但是当涉及到多维数组时……情况有所不同。我收到一条错误消息,指出未定义索引。有人可以帮助我吗?
我已经解决了这个类的问题。稍后我将在这里发布一个完整的工作示例,也许有人会需要它。感谢大家抽出时间阅读本帖
更新:那么你们怎么看?我应该做哪些改进...改变?
public function __construct(Array $properties)
{
$this->populateArray($properties);
}
private function populateArray(Array $array)
{
if(is_array($array))
{
foreach($array as $key => $value)
{
$this->createProperty($key, $value);
}
}
unset($this->properties);
}
private function createProperty($key, $value)
{
is_array($value) ?
$this->offsetSet($key, $this->createComplexProperty($value))
: $this->offsetSet($key, $value);
}
private function createComplexProperty(Array $array)
{
return new Config($array);
}
private function createPropertyIfNone($key)
{
if($this->offsetExists($key))
return;
$this->createProperty($name, array());
}
public function __get($key)
{
$this->createPropertyIfNone($key);
return $this->offsetGet($key);
}
public function __set($key, $value)
{
$this->createProperty($key, $value);
}
public function __ToString()
{
return (string) $value;
}
}