Skip to content

Instantly share code, notes, and snippets.

@rsky
Last active December 17, 2015 12:39
Show Gist options
  • Save rsky/5610891 to your computer and use it in GitHub Desktop.
Save rsky/5610891 to your computer and use it in GitHub Desktop.
from collection import defaultdict
<?php
class DefaultDict extends ArrayObject
{
private $ctor;
public function __construct($ctor, array $ary = [])
{
if (is_array($ctor)) {
list($class, $method) = $ctor;
if (is_object($class)) {
$this->ctor = function () use ($class, $method) {
return $class->$method();
};
} else {
$this->ctor = function () use ($class, $method) {
return $class::$method();
};
}
} else {
$this->ctor = $ctor;
}
parent::__construct($ary);
}
public function offsetExists($key)
{
return true;
}
public function offsetGet($key)
{
if (parent::offsetExists($key)) {
return parent::offsetGet($key);
}
$ctor = $this->ctor;
$value = $ctor();
$this->offsetSet($key, $value);
return $value;
}
}
<?php
require 'DefaultDict.php';
error_reporting(E_ALL);
function wc($s, DefaultDict $d) {
foreach (str_split($s) as $c) {
$d[$c] += 1;
}
print_r((array)$d);
}
class X {
public function int() { return 0; }
public static function integer() { return 0; }
}
$s = 'abracadabra';
wc($s, new DefaultDict(function(){ return 0; }));
wc($s, new DefaultDict(['X', 'integer']));
wc($s, new DefaultDict([new X, 'int']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment