Search code examples
phptypesparametersstrictmixed

How to use mixed parameter type in my own functions?


I want to define a PHP 7 function that takes a parameter of mixed type. (What I want is the equivalent of a generic type parameter in C#; if there's a better way to emulate that in PHP 7, please let me know.)

My code is as follows.

<?php
declare (strict_types = 1);    

function test (mixed $s) : mixed {
    return $s;
}

// Works
echo gettype ('hello');
// Does not work
echo test ('hello');
?>

When I run this code, I get the following.

Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of mixed, string given, called in mixed.php on line 11 and defined in mixed.php:4
Stack trace:
#0 mixed.php(11): test('hello')
#1 {main}
thrown in mixed.php on line 4

If I comment out the call to test(), the code runs fine, so apparently it's at least okay for me to use the mixed parameter type in the function declaration.

I know built-in PHP functions such as gettype() can take mixed parameters, though I don't know if they are internally using strict typing.

I see that "mixed" is also used as a pseudo-type in PHP documentation, so I might misunderstand the purpose of "mixed" as a PHP keyword, but what I'm seeing here at least implies to me that it is a legitimate keyword. Am I simply using it in a way it isn't intended for?

Finally, I realize I could circumvent all this by simply not specifying the parameter type, but I'd like to be consistent by specifying all my parameter and return types.

Thank you and please let me know if I can provide any additional information.


Solution

  • FYI mixed is not a Type. (Refer to the Documentation). It is only a pseudo type: a Hint that any Type might be passed to or returned from a Method... or perhaps for a variable which was loosely typed as mixed for any reason...

    Unlike in C#, what you are trying to achieve might be tricky in PHP especially with strict_types set to true.

    However, you can achieve a nearly similar effect without Strict Typing - in which case your Methods may accept any Type so long as you don't supply any Type Hints. Though For C# Programmers, that's bad - yet, that is the juice of PHP.