How to create a generic‑like method in PHP

3 Answers

0 votes
class Utils
{
    /**
     * @template T
     * @param T $value
     * @return T
     */
    public static function identity($value) {
        return $value;
    }
}

echo Utils::identity(123) . PHP_EOL;        // int
echo Utils::identity("Hello") . PHP_EOL;    // string
echo Utils::identity(3.14) . PHP_EOL;       // float



/*
run:

123
Hello
3.14

*/

 



answered 3 hours ago by avibootz
0 votes
// Generic Swap Method

class Utils
{
    /**
     * @template T
     * @param array<int, T> $arr
     * @param int $i
     * @param int $j
     * @return void
     */
    public static function swap(array &$arr, int $i, int $j): void
    {
        $temp = $arr[$i];
        $arr[$i] = $arr[$j];
        $arr[$j] = $temp;
    }
}

// Test with integers
$numbers = [10, 20, 30, 40];
Utils::swap($numbers, 1, 3);
print_r($numbers);

// Test with strings
$words = ["PHP", "Java", "Python"];
Utils::swap($words, 0, 2);
print_r($words);



/*
run:

Array
(
    [0] => 10
    [1] => 40
    [2] => 30
    [3] => 20
)
Array
(
    [0] => Python
    [1] => Java
    [2] => PHP
)

*/

 



answered 3 hours ago by avibootz
0 votes
// Generic Pair Method

class Utils
{
    /**
     * @template K
     * @template V
     * @param K $key
     * @param V $value
     * @return void
     */
    public static function printPair($key, $value): void
    {
        echo $key . " = " . $value . PHP_EOL;
    }
}

Utils::printPair("Age", 42);
Utils::printPair(101, "Employee ID");
Utils::printPair("Pi", 3.14159);



/*
run:

Age = 42
101 = Employee ID
Pi = 3.14159

*/

 



answered 3 hours ago by avibootz
...