最近做项目,遇到将函数转为闭包的场景,所以记录一下:
- 将当前类下的 writeLog 方法,转化为闭包函数
$fn = Closure::fromCallable([$this, 'writeLog']);
$fn('hello');
- 将php自带的函数转为闭包函数
$fnStr = Closure::fromCallable('strlen');
var_dump($fnStr('hello'));
- 将另一个类的静态方法转化为闭包函数
$fnRead = Closure::fromCallable([TopicRepository::class, 'readLog']);
var_dump($fnRead());
