tags:

views:

33

answers:

4

$array[(object)$obj] = $other_obj;

PHP arrays only work with indexes having scalar data types like int, string, float, boolean, null. I can't use objects as array index as in other languages? So how can I achieve an object->object mapping?

(I though I've seen something like this around here, but don't remember exactly and my search creativity is outworn.)

+2  A: 

http://php.net/manual/en/function.spl-object-hash.php

stereofrog
Ha! Nice. That wasn't it, but seems the best alternative. The handle hash seems to be like a pointer; they should add a reverse function.
mario
+1  A: 

If you need to be able to recreate the object from the key, you could use serialize($obj) as the key. To recreate the object call unserialize.

Mike C
A: 

Still didn't find the original, but remembered the actual trick, so I reimplemented it:
(my internet connection being down yesterday gave me the time)

class FancyArray implements ArrayAccess {

    var $_keys = array();
    var $_values = array();

    function offsetExists($name) {
        return $this->key($name) !== FALSE;
    }

    function offsetGet($name) {
        $key = $this->key($name);
        if ($key !== FALSE) {
            return $this->_values[ $key ];
        }
        else {
            trigger_error("Undefined offset: {{$name}} in FancyArray __FILE__ on line __LINE__", E_USER_NOTIC
            return NULL;
        }
    }

    function offsetSet($name, $value) {
        $key = $this->key($name);
        if ($key !== FALSE) {
            $this->_values[$key] = $value;
        }
        else {
            $key = end(array_keys($this->_keys)) + 1;
            $this->_keys[$key] = $name;
            $this->_values[$key] = $value;
        }
    }

    function offsetUnset($name) {
        $key = $this->key($name);
        unset($this->_keys[$key]);
        unset($this->_values[$key]);
    }

    function key($obj) {
        return array_search($obj, $this->_keys);
    }
}

It's basically ArrayAcces and a disparage array for keys and one for values. Very basic, but it allows:

$x = new FancyArray();

$x[array(1,2,3,4)] = $something_else;   // arrays as key

print $x[new SplFileInfo("x")];    // well, if set beforehand
mario
A: 

It sounds like you want to rediscover the SplObjectStorage class, which can provide a map from objects to other data (in your case, other objects).

It implements the ArrayAccess interface so that you can even use your desired syntax like $store[$obj_a] = $obj_b.

salathe
Though that particular feature only works on > 5.3
mario