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

报告相同问题?