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.
mixed
is not a real type. And being consistent is orthogonal to proper semantics here. – Grindelia@param mixed $s
to document your method, then phpStorm will not complain about the missing type – Graphicshttps://www.php.net/manual/en/language.pseudo-types.php
is a dead link. – Shue