Strings\stringCompiler()

accumulator returns Closure pure
string → (string? → Closure | string)
At a glance — Self-returning accumulator for building strings across calls. Call with null (or no argument) to read the final result.

Creates a self-returning accumulator that builds up a string across successive calls. Each call with a non-empty string returns a new compiler Closure with that value appended; calling the compiler with null (or no argument) returns the final compiled string.

/**
  * @param string $initial Optional seed string. Defaults to ''.
  * @return Closure(string|null):(Closure|string)
  */
Strings\stringCompiler(string $initial = ''): Closure

Returned Closure

When Strings\stringCompiler() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param string|null $value  Chunk to append, or null to finalise.
  * @return Closure|string     Closure while still accumulating, string once finalised.
  */
$function (?string $value = null)

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

// Seed the compiler with a prefix — each call returns a new compiler.
$compiler = Strings\stringCompiler('Log: ');

// Append values step by step. Every append returns a fresh compiler.
$compiler = $compiler('one ');
$compiler = $compiler('two ');
$compiler = $compiler('three');

// Call with no argument (or null) to read the accumulated string.
echo $compiler(); // Log: one two three

Curried

This can be called inline using currying.

// Chain the calls inline — every () appends; the final empty () finalises.
echo Strings\stringCompiler('Hello ')('world')('!')(); // Hello world!

Inlined with Higher Order Function

If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.

// Fold an array of chunks into a single string.
$parts = ['The ', 'quick ', 'brown ', 'fox'];

$compiled = array_reduce(
  $parts,
  fn($acc, $chunk) => $acc($chunk),
  Strings\stringCompiler()
);

echo $compiled(); // The quick brown fox

Details

Strings Functions

Releated String manipulation Functions