Created
October 13, 2012 16:18
-
-
Save scribu/3885198 to your computer and use it in GitHub Desktop.
defaultdict in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$instances = new Defaultdict( function( $key ) { | |
$value = new stdClass; | |
$value->id = $key; | |
return $value; | |
} ); | |
print_r( $instances['bar'] ); // Result: stdClass Object ( [id] => bar ) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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