gpt4 book ai didi

php - 使用 ArrayObject 的配置类

转载 作者:搜寻专家 更新时间:2023-10-31 21:12:16 32 4
gpt4 key购买 nike

我一直在寻找一种方法来实现 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;
}
}

最佳答案

如果您想假设一个不存在的键是一个数组,那么这应该可行。

public function __get($key)
{
if(!$this->offsetExists($key))
{
$this->offsetSet($key,new Array());
}
return &$this->offsetGet($key);
}

用法:

$config = new Config\Config($settings);
$config->url['uri'] = 'localhost';
print_r($config);

编辑:

不确定是否必须返回引用才能使它起作用。

    return &$this->offsetGet($key);

或者这个

    return $this->offsetGet($key);

关于php - 使用 ArrayObject 的配置类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16944599/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com