- print_r: documentation ( source)
<?php
// modified from: http://us1.php.net/manual/en/class.arrayaccess.php#99236
// sanity and error checking omitted for brevity
// note: it's a good idea to implement arrayaccess + countable +
// an iterator interface (like iteratoraggregate) as a triplet
/*
// WORKS.
class Template implements ArrayAccess {
// makes it so we can do $template_inst['foo'];
public $config = array();
// necessary for deep copies
public function __clone() {
foreach ($this->config as $key => $value) if ($value instanceof self) $this[$key] = clone $value;
}
public function __construct(array $config = array()) {
foreach ($config as $key => $value) $this[$key] = $value;
}
public function offsetSet($offset, $config) {
if (is_array($config)) { $config = new self($config); }
if ($offset === null) { // don't forget this!
$this->config[] = $config;
} else {
$this->config[$offset] = $config;
}
}
public function toArray() {
$config = $this->config;
foreach ($config as $key => $value) if ($value instanceof self) $config[$key] = $value->toArray();
return $config;
}
// as normal
public function offsetGet($offset) { return $this->config[$offset]; }
public function offsetExists($offset) { return isset($this->config[$offset]); }
public function offsetUnset($offset) { unset($this->config); }
}
*/
// DOESN'T WORK
class Template implements ArrayAccess {
// makes it so we can do $template_inst['foo'];
// container for items passed with null $offset: $this[] = $value;
public $implied_key_list = array();
// necessary for deep copies
public function __clone() {
foreach ($this as $key => $value) if ($value instanceof self) $this[$key] = clone $value;
}
public function __construct(array $items = array()) {
foreach ($items as $key => $value) { $this[$key] = $value; }
}
public function offsetSet($offset, $value) {
// if (is_array($value)) { $value = new self(array($offset => $value)); } # segfault from this line
if ($offset === null) { // don't forget this! allows `$this[] = $value;`
$this->implied_key_list[] = $value;
} else {
$this->$offset = $value;
}
}
// as normal
public function offsetGet($offset) { return $this->$offset; }
public function offsetExists($offset) { return isset($this->$offset); }
public function offsetUnset($offset) { unset($this->$offset); }
}
$test = new Template(array('noises' => array('dog' => 'woof')));
echo "<pre><code>";
print_r($test);
echo "</code></pre>";