I was trying out PHP's mixed
type in a custom function, but this error has me stumped (punctuation is mine):
TypeError: Argument 1 passed to <functionName>() must be an instance of
mixed
,string
given.
Below some (sample) code below that causes the error message and illustrates what I was hoping to achieve. Below that some TLDR with further explanation. But basicall I saw mixed
as the type of parameters of some of PHP's native functions (for example the is_string function) and wanted to do the same in a custom function.
How can I explicitly specify that a function parameter is multitype/mixed/any?
Code
<?php
function echoMixed(mixed $input) {
if (!is_array($input)) {
echo mixed;
} else {
// For arrays echo each element using recursive call.
foreach($input as $current) {
echoMixed($current);
}
}
}
echoMixed('test'); // <-- This results in the error.
echoMixed(['test1', 'test2']);
?>
TLDR
I'm pretty new to PHP, but was trying out the 'new' explicit type system. I'm using PHP 7.x but I think this was introduced in PHP 5.0. I love the system of optional typing of the TypeScript language, and initially assumed mixed
works the same was as the type any
in TypeScript. The PHP documentation on mixed only strengthened this assumption because it states:
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
But after receiving this error it seems as though mixed
is something completely different. Is this intended for arrays with values of mixed type or something?
To achieve what you want you just have to leave out
mixed
and not specify a typehint. PHP does NOT have a language keyword to explicitly specify an argument can be different types.Note that
mixed
IS named a keyword in the documentation, but it is not a 'language keyword', but a keyword only within the PHPDocs. The same goes forarray|object
,number
,void
, and the other pseudo-types. Actual types that you can use in code are namedprimitives
in PHP, see the below excerpts from documentation.Allowed typehints in PHP code
Here are the allowed types and the minimum PHP version to use them:
PHP 8.0 also introduces union types with the following syntax :
bool|string
which will allow booleans or strings. (rfc)Warning:
integer
andboolean
cannot be used as typehintsSource: http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
Allowed types in PHPdoc comments
PHP primitive types
Keywords (non native to PHP)
Source: https://www.phpdoc.org/docs/latest/guides/types.html#primitives
Update 2021
mixed
type has been introduced in PHP8static
type has been introduced in PHP8