PHP code example of upscale / stdlib-overloading

1. Go to this page and download the library: Download upscale/stdlib-overloading library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

upscale / stdlib-overloading example snippets



declare(strict_types=1);

use function Upscale\Stdlib\Overloading\overload;

function func(...$args)
{
    return overload(
        function (int $num1, int $num2) {
            // ...
        },
        function (string $str1, string $str2) {
            // ...
        }
        // ...
    )(...$args);
}

func(1, 2);
func('a', 'b');


declare(strict_types=1);

use function Upscale\Stdlib\Overloading\overload;

class Money
{
    private $amount;
    private $currency;

    public function __construct(int $amount, string $currency)
    {
        $this->amount = $amount;
        $this->currency = $currency;
    }

    public function add(self $sum): self
    {
        if ($sum->currency != $this->currency) {
            throw new \InvalidArgumentException('Money currency mismatch');
        }
        return new self($this->amount + $sum->amount, $this->currency);
    }
}

class Calculator
{
    public function add(...$args)
    {
        return overload(
            function (int $num1, int $num2): int {
                return $num1 + $num2;
            },
            function (\GMP $num1, \GMP $num2): \GMP {
                return gmp_add($num1, $num2);
            },
            function (Money $sum1, Money $sum2): Money {
                return $sum1->add($sum2);
            }
        )(...$args);
    }
}


$calc = new Calculator();

$one = gmp_init(1);
$two = gmp_init(2);

$oneUsd = new Money(1, 'USD');
$twoUsd = new Money(2, 'USD');

print_r($calc->add(1, 2));
// 3

print_r($calc->add($one, $two));
// GMP Object([num] => 3)

print_r($calc->add($oneUsd, $twoUsd));
// Money Object([amount:Money:private] => 3 [currency:Money:private] => USD)

print_r($calc->add(1.25, 2));
// TypeError: Argument 1 passed to Calculator::{closure}() must be an instance of Money, float given

overload(
    function (int $num1, int $num2) {
        // ... 
    },
    function (int $num1) {
        // ... 
    },
    function (int $num1, string $str2 = 'default') {
        // Unreachable because preceding declaration matches first and swallows excess arguments
        // ...
    }
)

overload(
    function (int $num1, int $num2) {
        // ... 
    },
    function (int $num1) {
        if (func_num_args() > 1) {
            throw new \ArgumentCountError('Too many arguments provided');
        }
        // ... 
    },
    function (int $num1, string $str2 = 'default') {
        // Reachable with the optional argument passed, but still unreacable without it
        // ... 
    }
)