Last active
October 8, 2015 10:07
-
-
Save yuya-takeyama/3316674 to your computer and use it in GitHub Desktop.
PHP で関数合成 ref: http://qiita.com/yuya_takeyama/items/858c5a0652441f54f0a8
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 ComposableFunction | |
{ | |
/** | |
* @var callable | |
*/ | |
private $fn; | |
/** | |
* Constructor | |
* | |
* @param callable $fn | |
*/ | |
public function __construct(callable $fn) | |
{ | |
$this->fn = $fn; | |
} | |
/** | |
* Invokes function | |
*/ | |
public function __invoke() | |
{ | |
return call_user_func_array($this->fn, func_get_args()); | |
} | |
/** | |
* Composes new function | |
*/ | |
public function compose(callable $fn) | |
{ | |
return new static(function () use ($fn) { | |
return $fn(call_user_func_array($this, func_get_args())); | |
}); | |
} | |
} | |
$splitWithUnderscore = new ComposableFunction(function ($str) { | |
return explode('_', $str); | |
}); | |
$mapUcfirst = function ($words) { | |
return array_map('ucfirst', $words); | |
}; | |
$camelize = $splitWithUnderscore->compose($mapUcfirst)->compose('join'); | |
var_dump($camelize('foo_bar_baz')); | |
// => FooBarBaz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment