php - 不能使用类型的对象 XXX 作为数组
问题描述
我正在运行引发错误的函数:
不能使用类型为数组的对象 Coalition/ConfigRepository
为了解决这个问题,我需要更改扩展类“ConfigRepository”
<?php
use Coalition\ConfigRepository;
class ConfigRepositoryTest extends PHPUnit_Framework_TestCase
public function test_array_access_set()
{
$config = new ConfigRepository;
$config['foo'] = 'bar'; //throw error here
$this->assertTrue(isset($config['foo']));
$this->assertEquals('bar', $config['foo']);
}
}
public function test_array_access_unset()
{
$config = new ConfigRepository(['foo' => 'bar']);
unset($config['foo']);
$this->assertFalse($config->has('foo'));
}
扩展类是我必须改变的地方
namespace Coalition;
class ConfigRepository
{
private $key=[];
/**
* ConfigRepository Constructor
*/
public function __construct($key = null)
{
$this->key = $key;
}
public function has($key)
{
if(!$this->key) return false;
return array_key_exists($key,$this->key);
}
}
我该如何解决?
也许问题出__construct
在我必须传递数组值的地方?
解决方案
最简单的解决方法是将$key
成员公开。所以第一个变化是class ConfigRepository
:
public $key=[];
然后你可以这样做:
public function test_array_access_set() {
$config = new ConfigRepository(array("foo" => "bar")); // set the value in the constructor
// access the $config->key as you array and check what you need
$this->assertTrue(isset($config->key['foo']));
$this->assertEquals('bar', $config->key['foo']);
}
如果你能改变的只是你应该做的 ConfigRepository 类:
class ConfigRepository implements ArrayAccess {
private $container = array();
public function __construct($arr ) {
$this->container = $arr;
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
public function offsetSet($offset, $value) {
if (is_null($offset))
$this->container[] = $value;
else
$this->container[$offset] = $value;
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
}
推荐阅读
- kinect - Xbox 360 Kinect 与 MS Teams 一起用作网络摄像头摄像头驱动程序运行时,仅将设备识别为音频
- java - 使用多个源值时,有没有办法为 Mapstruct 指定默认输入参数?
- reactjs - 尝试将 Blob 对象设置为 React State 挂钩
- javascript - Web 组件加载未知组件
- amazon-web-services - 使用 codepipeline 的 AWS API-Gateway 蓝/绿部署
- amazon-web-services - 如何在 lambda 退出时发送一些事件
- c++ - 在 CLion 上为 VS 编译器配置 SFML
- android - 预期 BEGIN_ARRAY 但为 STRING,如何将 STRING 转换为空 ARRAY?
- c# - 是否可以从 .net core 3.1 Windows 服务打印文档?
- javascript - 在 EChart 上画圆