Skip to content

Instantly share code, notes, and snippets.

@scribu
Created October 13, 2012 16:18
Show Gist options
  • Save scribu/3885198 to your computer and use it in GitHub Desktop.
Save scribu/3885198 to your computer and use it in GitHub Desktop.
defaultdict in PHP
<?php
# http://scribu.net/blog/defaultdict-in-php.html
class Defaultdict implements ArrayAccess {
private $container = array();
private $default;
public function __construct( $default ) {
$this->default = $default;
}
public function offsetSet( $offset, $value ) {
if ( is_null($offset) ) {
trigger_error( sprintf( "Trying to use %s as a list.", __CLASS__ ), E_USER_WARNING );
return;
}
$this->container[$offset] = $value;
}
public function offsetExists( $offset ) {
return true;
}
public function offsetUnset( $offset ) {
unset( $this->container[$offset] );
}
public function &offsetGet( $offset ) {
if ( !isset( $this->container[$offset] ) ) {
if ( is_callable($this->default) )
$value = call_user_func( $this->default, $offset );
else
$value = $this->default;
$this->container[$offset] = $value;
}
return $this->container[$offset];
}
}
<?php
$instances = new Defaultdict( function( $key ) {
$value = new stdClass;
$value->id = $key;
return $value;
} );
print_r( $instances['bar'] ); // Result: stdClass Object ( [id] => bar )
<?php
$counts = new Defaultdict(1);
echo $counts['foo']; // Result: 1
$counts['bar']++;
echo $counts['bar']; // Result: 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment