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条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?