Skip to content

Instantly share code, notes, and snippets.

@gotohr
Last active December 25, 2015 16:19
Show Gist options
  • Save gotohr/7005203 to your computer and use it in GitHub Desktop.
Save gotohr/7005203 to your computer and use it in GitHub Desktop.
declarative function composition - PHP
<?php
use \Closure;
class Invokable {
private $closure;
public function __construct(Closure $closure) {
$this->closure = $closure;
}
public static function newInstance(Closure $closure) {
return new self($closure);
}
public function __invoke($arg) {
$c = $this->closure;
return $c($arg);
}
public function compose(Invokable $inner) {
$inv = $this;
return Invokable::newInstance(
function($i) use ($inv, $inner) {
return $inv($inner($i));
}
);
return $this;
}
}
$inv1 = Invokable::newInstance(
function($i) {
return $i * 2;
}
);
$inv2 = Invokable::newInstance(
function($i) {
return $i + 1;
}
);
$inv3 = Invokable::newInstance(
function($i) {
return $i + 10;
}
);
$inv = $inv1->compose($inv2)->compose($inv3);
echo ($inv(2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment