首页 > 解决方案 > 不能使用类型的对象 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在我必须传递数组值的地方?

标签: phparraysclassphpunit

解决方案


最简单的解决方法是将$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]);
    }

}

推荐阅读