【问题标题】:can not use object XXX of type as array不能使用类型的对象 XXX 作为数组
【发布时间】:2019-12-01 04:39:51
【问题描述】:

我正在运行抛出错误的函数:

不能将对象 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 我必须传递数组值的地方?

【问题讨论】:

  • 错误很明显 - 对象不是数组。你想达到什么目标?你想让 ConfigRepository 保存关联数组吗?如果$key 是私有的,你至少应该有get 方法(如果没有设置/附加)
  • 我想解决这个错误,因为我必须在下面的类中更改,值应该是数组,请通过更改类配置存储库更新答案

标签: php arrays class phpunit


【解决方案1】:

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

}

【讨论】:

  • 我不能在 test_array_access_set() 函数中改变,而我只需要改变 ConfigRepository 类
  • 所以你宁愿改变类而不是改变对象??太奇怪了...在这种情况下,请查看:php.net/manual/en/class.arrayaccess.php 了解如何实现类似数组的对象(以及此处:stackoverflow.com/questions/56566262/…
  • 是的,我已经通过了所有这些方法,只是这个不起作用
  • @KetanBorada 这是完整示例的链接:3v4l.org/4qbTg。我不知道我还能提供什么帮助 - 也许您的问题在别处。
  • ArrayAccess 是成功的关键
猜你喜欢
  • 2021-12-17
  • 2012-01-19
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多