Complex type as array index

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

PHP arrays only work with indexes that have scalar data types such as int, string, float, boolean, null. I can not use objects as an index of an array, as in other languages? So how can I achieve object mapping of objects?

(Although I saw something like this here, I don’t remember exactly, and my search creativity is exhausted.)

+4
source share
4 answers

It looks like you want to reopen 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 use your desired syntax, for example $store[$obj_a] = $obj_b .

+2
source

If you need to recreate an object from a key, you can use serialize($obj) as the key. To recreate a call to an unserialize object.

+2
source

Still did not find the original, but remembered the trick, so I repeated it:
(yesterday my internet connection gave me 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); } } 

This is mainly ArrayAcces and a disparage array for keys and one for values. Very simple, but it allows you to:

 $x = new FancyArray(); $x[array(1,2,3,4)] = $something_else; // arrays as key print $x[new SplFileInfo("x")]; // well, if set beforehand 
+1
source

Source: https://habr.com/ru/post/894773/


All Articles