Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么';无法在实现ArrayAccess接口的对象上使用数组函数_Php_Arrays_Interface - Fatal编程技术网

Php 为什么';无法在实现ArrayAccess接口的对象上使用数组函数

Php 为什么';无法在实现ArrayAccess接口的对象上使用数组函数,php,arrays,interface,Php,Arrays,Interface,我从php文档中得到了这个obj类: class obj implements ArrayAccess { private $container = array(); public function __construct() { $this->container = array( "one" => 1, "two" => 2, "three" => 3,

我从php文档中得到了这个
obj
类:

class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}
现在,当我尝试使用in_数组函数时,比如

$obj = new obj;
echo in_array('1', $obj);
我得到一份工作

Warning: in_array() expects parameter 2 to be array, object given

实现ArrayAccess的对象不应该像实际的数组一样工作吗?

imo,我怀疑这是他们的魔法,PHP
Array.*
函数使用
数组的内部结构。无论如何,大多数时候,当我实现一个实现
array
接口的类时,我会扩展
ArrayObject
或在内部使用数组。因此,我总是提供一个名为
toArray()
的方法和另一个名为
fromArray($array)
的方法,它们可以满足您的需求。这些通常写起来很便宜,因为这只意味着返回我正在使用的内部数组。这样,如果需要,我仍然可以将它们与PHP
array\u*
函数一起使用。@RyanVincent这种方法的问题是,如果您使用的是第三方软件包,希望能够直接将对象用作数组。@alexw,很好奇,你有这样一个第三方软件包的例子吗?我目前正在尝试获取一个
ArrayAccess
对象作为Slim 3中的配置服务。它使用
array\u merge
将用户设置(预期为数组)与默认设置相结合。@alexw,显然,您不能通过设置传递配置对象。这没关系,因为我假设您希望使用配置而不是设置数组。我将使用以下示例:。我不使用slim,但我使用了Pimple:)。您需要为您的配置添加一个条目:即..$container['config']=函数($container){returnnewconfigula\config(APP_config_ROOT);};我使用config类。另见。