In php I always check a variable for the exact type, like if ($myVariable instanceof MyClass)
.
I check at least if its null, if its not an object if ($myVariable === null)
.
If I really just need to know if it is empty I use if (empty($myVariable))
.
But I never use if ($myVariable)
because this syntax often does more than what was intended, and pushes me to check the code twice. It even sometimes persuades developers to use empty strings or other "empty equal" values, when instead null should be used.
But in the case of typehinting like this:
public function myMethod (?MyClass $myVariable)
{
if ($myVariable === null) {
[...]
if ($myVariable === null)
, if (!$myVariable)
, and if (!$myVariable instanceof MyClass)
would result in the exact same behaviour.
Is there a reason for preferring if (!$myVariable)
, over if (!$myVariable instanceof MyClass)
, or if ($myVariable === null)
or the other way around, if a variable was type hinted before?
My Answer:
In this case, it is generally considered clean code to use if ($myVariable) when $myVariable is type hinted in PHP. This is because the type hinting ensures that $myVariable will always be an instance of MyClass or null, so checking for null with if ($myVariable === null) is redundant. Using if (!$myVariable) is a more concise and clear way to check if $myVariable is not null.
However, if there is a specific reason to check if $myVariable is an instance of MyClass, then using if (!$myVariable instanceof MyClass) would be more appropriate. It ultimately depends on the specific requirements of the code and what needs to be checked.
Overall, as long as the code is clear, concise, and accurately reflects the intended behavior, using if ($myVariable) when $myVariable is type hinted in PHP can be considered clean code.
Rate this post
4 of 5 based on 7635 votesComments