5
votes

I am coming from a strictly typed programming language, which has a type named "ANY".

Because PHP is loosely coupled, I would need for my PhpDoc some sort of type hinting saying that the variable, parameter or return value can be of any type. At the moment I have to write something like:

@var string|int|bool|array|object $someVariable

It would make my life easier and the code would be much easier to read if I could write instead:

@var any $someVariable

I am actually having this problem in many cases - more than 20-30 times by now in the last months, since I use PhpStorm, which is showing me warnings that some other kind of parameter type is expected for some method, either because I forgot to put it explicitly in the list of types or because I am using code written in Eclipse, which did not show any warnings for my self-proclaimed "any" type.

My question: is there a way to tell PhpStorm that when I say any I actually mean string|any|bool|array|object or is there some other type hint which says that? I am also curious if I am the only one having this issue or if there are some others working like this.

3
@var mixed $someVariable ? - maximkou

3 Answers

9
votes

You should use "mixed" for that. Also with PHP7.0 there is actual type hinting for parameters and return values.

2
votes

PHP

Pseudo-types and variables

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.

PHP Manual

PHPDoc

mixed, the element to which this type applies can be of any type as specified here. It is not known on compile time which type will be use.

PSR-5

Example

/**
 * Counts the number of items in the provided array.
 *
 * @param mixed[] $items Array structure to count the elements of.
 *
 * @return int Returns the number of elements.
 */
function count(array $items)
{
    <...>
}
0
votes

As you have two questions, I have two answers. You're asking what would be good practices when it comes to multiple return types. A good practice would be to not do this at all. (Always) make sure your methods only return one type. This will not only make your methods cleaner, but also the code that calls the method; You won't have to check for types ever, and you always know what you get as a return value, and therefore you will know what you can do with it. This is not a hard practice to live by with some architecture skills.