Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Function composition

Compose callables by passing the entire return value of the first as the argument of the next.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

fn($x) => $after($before($x));

Compose callables by passing the entire return value of the first as the argument of the next. Order can change the result even with pure functions. Use compatible parameter and return types. Any exception raised by an earlier stage prevents later stages from running.

function then(callable $first,callable $next):Closure{return fn(int $x)=>$next($first($x));}
$add=fn(int $v)=>$v+2;$double=fn(int $v)=>2*$v;echo json_encode([then($add,$double)(3),then($double,$add)(3)]);
[10,8]

Examples

<?php
function then(callable $first,callable $next):Closure{return fn(int $x)=>$next($first($x));}
$add=fn(int $v)=>$v+2;$double=fn(int $v)=>2*$v;echo json_encode([then($add,$double)(3),then($double,$add)(3)]);

Result

[10,8]

Sources