duanhuan6336 2014-02-26 18:56
浏览 42
已采纳

PHP:使对象像数组一样[关闭]

I am writing a class (Hash) that adds behaviour to array. The instantiated objects should be interchangeable with the primitive array, so I can pass it to methods that require arrays. Also I want to be able to cast the object to array

The test it should pass is here.

I thought implementing ArrayAccess would be enough, but it is not.

Or perhaps implementing a __toArray() method, like toString() for casting strings, but it also won't work.

edit:

$hash = new Hash(array(
    'foo' => 'bar',
    'bar' => 'barfoo',
));

function echoArray(array $array) {
    print_r($array);
}

echoArray($hash); 
// Catchable fatal error: Argument 1 passed to echoArray() 
// must be of the type array, object given

print_r((array) $hash);
/*
Array
(
    [*_values] => Array
        (
            [foo] => bar
            [bar] => barfoo
        )
)
*/

Is there a way of achieving that behaviour?

Thank you in advance.

  • 写回答

3条回答 默认 最新

  • duanjurong1347 2014-02-26 19:10
    关注

    It's sadly not possible for a lot of internal functions that require primitive arrays to use your object as such. Yes, user defined PHP function can use it as an array (although not if you require an argument to be a primitive array), but stuff like array_map... won't:

    <?php
    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;
        }
    }
    
    $obj = new obj;
    
    function requirearray(array $obj){};
    
    requirearray($obj);
    // Catchable fatal error: Argument 1 passed to requirearray() must be of the type array, object given...
    
    var_dump(array_map('strlen',$obj));
    // Warning: array_map(): Argument #2 should be an array
    // NULL
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料