Is it good practice to have properties like this:
/**
* @var false|array|null
*/
protected $mockMethods = false;
This property can be either false
or array
or null
.
Or perhaps its better to have just one data type for internal class properties?
As a general rule, I would say "no". Mainly because you would probably end up adding additional type checking against the variable type in your code. That said: I've seen it done plenty of times, including in the return values op PHP built in functions. So I can't really claim it's 'off-limits' or anything!
There is a lot of functions - including built-in ones - that return aither a string or array, false
or null
.
In these cases, the reason is that the function's primary purpose is to return a string or array. false
is usually returned if the operation doesn't apply - for example if you call strpos()
on a string that doesn't contain the substring you are looking for - while null
will be specifically returned if an error occured somewhere.
But your question is about variables, properties to be more precise. While a variable used to recover the return of a function which can return three different types depending on the case can be assigned any of these types, storing that uncertain information is unwise.
When a value comes from a function that can return several differet types, you have to test it before using it. The sooner you test it and assert its nature, the sooner you can act accordingly.
If you just assign that return to your property and tests its type when you use it, it means you will have to test it everytime you need it. Moreover, if an error happened, you store an useless null
in a property and only detect the error when you need the value.
A good way to make programs is to design your variable according to what they will contain and what will be done to/with it. It makes your code more obvious and can help you to prevent errors.
Check the type and eventually the content of values returned by functions before storing them so that you can stand on your stored values.
To make a parallel with real life, assigning values from functions to properties without checking and filtering them is like hiring people as soon as they contact you and interviewing them only when - and therefore each time - you need to put them on a task. Needless to say its tedious, messy and prone to error.