Usephul

functions.php

Tags
author

Alwin Garside alwin@garsi.de

copyright

2025 The Empaphy Project

license

MIT

Table of Contents

Functions

fit()  : TResult
Returns the result of the first callback with a parameter type that fits the type of the given value.

Functions

fit()

Returns the result of the first callback with a parameter type that fits the type of the given value.

fit(TSubject $subject, callable(TFit $arg, TFit ...$args): TResult $callback, callable(TFit $arg, TFit ...$args): TResult ...$callbacks) : TResult

This function functions similar to a match or switch statement but uses type checks to gauge which expression to evaluate for subject.

use function empaphy\usephul\fit;

$result = fit(
    $example,
    fn(string $v): string      => "value '$v' is a string",
    fn(int|float $v)           => "value is an integer or float",
    fn(array $v, object $w)    => "value is an array or an object",
    fn(Foo&(Bar|(Baz&Qux)) $v) => "both `Foo` & `Bar` or `Baz` & `Qux`",
    fn(mixed $default)         => "value is of some other type",
);

fit() is optimized for performance and makes no recursive calls, or calls to any other helper functions; it's completely self-contained.

Parameters
$subject : TSubject

The value to gauge.

$callback : callable(TFit $arg, TFit ...$args): TResult

A callback function. The first callback argument with a parameter type that fits subject will be called and its result returned.

$callbacks : callable(TFit $arg, TFit ...$args): TResult

Additional callback functions. The first callback function with a parameter type that fits subject will be called and its result returned.

Return values
TResult

The result of the first of the callbacks that fits subject.


        
On this page

Search results