I want to define a PHP 7 function that accepts a mixed type parameter. (What I want is the equivalent of a generic type parameter in C #, if there is a better way to emulate this 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 on the test () call, the code works fine, so it seems to me at least suitable for using a mixed parameter type in a function declaration.
I know that PHP built-in functions like gettype () can accept mixed parameters, although I donβt know if they internally use strong typing.
I see that βmixedβ is also used as a pseudo-type in the PHP documentation , so I might misunderstand the purpose of βmixedβ as the PHP keyword, but what I see here at least implies that it is legal keyword. Am I just using it the way it is not intended?
Finally, I understand that I can get around all this by simply not specifying the type of parameter, but I would like to be consistent by specifying all my parameters and return types.
Thank you, and please let me know if I can provide more information.
types php parameters strict
FSharpN00b
source share