Last active
December 17, 2015 12:39
-
-
Save rsky/5610891 to your computer and use it in GitHub Desktop.
from collection import defaultdict
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 | |
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; | |
} | |
} |
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 | |
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