Created
May 6, 2011 04:51
-
-
Save dhotson/958457 to your computer and use it in GitHub Desktop.
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 | |
$array = function() { | |
$elements = func_get_args(); | |
$result = fn(function($i) use ($elements) { | |
return $elements[$i]; | |
}); | |
$result->len = function() use ($elements) { | |
return count($elements); | |
}; | |
$result->each = function($fn) use ($elements) { | |
foreach ($elements as $e) | |
$fn($e); | |
}; | |
return $result; | |
}; | |
$a = $array('yabba', 'dabba', 'doo'); | |
echo "1st element: ".$a(0)."\n"; | |
echo "length: ".$a->len()."\n"; | |
$a->each(function($e) { | |
echo " - $e\n"; | |
}); | |
// PHP doesn't let you set properties on a Closure object | |
// .. this is a decorator that allows you to. >:-) | |
class Fn | |
{ | |
private $_data; | |
function __construct($fn) | |
{ | |
$this->_fn = $fn; | |
} | |
function __invoke() | |
{ | |
$args = func_get_args(); | |
return call_user_func_array($this->_fn, $args); | |
} | |
function __call($name, $args) | |
{ | |
return call_user_func_array($this->$name, $args); | |
} | |
function __get($name) | |
{ | |
return $this->_data[$name]; | |
} | |
function __set($name, $val) | |
{ | |
return $this->_data[$name] = $val; | |
} | |
} | |
function fn($fn) { return new Fn($fn); }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment