PHP 7: How to use mixed parameter type in my own functions?

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.

+11
types php parameters strict
source share
2 answers

FYI mixed is not a type. ( Refer to the documentation ). This is just a pseudo-type : a hint that any type can be passed or returned from a method ... or perhaps for a variable that was freely printed as mixed for any reason ...

Unlike C #, what you're trying to achieve can be tricky in PHP, especially when strict_types is set to true .

However, you can achieve almost the same effect without strict typing - in this case your methods can accept any type if you don't give any type hints. Although this is bad for C # programmers , it is PHP juice .

+12
source share

To indicate that the function is also null, does that also work? -operator, as stated at http://php.net/manual/de/functions.returning-values.php#functions.returning-values.type-declaration

But this is only applicable if the code should not be backward compatible, because this function is available only in PHP> = 7.1. As you can see at https://wiki.php.net/rfc/mixed-typehint there as an RFC for adding a mixed type of hint. So in fact, there seems to be no chance of determining the correct type hint for parameters that accept more than one type.

So phpDoc comment may be a solution (and it is also backward compatible). Example:

 /** * Functiondescription * @author FSharpN00b * @param mixed $s * @return mixed **/ function test ($s){ return $s; } 
0
source share

All Articles