Home > Enterprise >  PHP 7 - Expected an object instance when accessing an instance property
PHP 7 - Expected an object instance when accessing an instance property

Time:09-28

I am using PHP Phan to scan through some code and ensure PHP 7 compatibility before upgrade. It is reporting an issue with the following...

if(!empty($values->custom_field['section'][0]['value'])):

Expected an object instance when accessing an instance property, but saw an expression $values with type null

I am not sure what is causing the error of how to resolve, can anyone help?

CodePudding user response:

$values is an object, since it needs to have a custom_field property. For some reason your tool believes $values to be null in that instance.

Why that should be the case, I do not know. I have seen this happen with code such as,

$values = null;
if (SOMETHING THAT SHOULD ALWAYS HAPPEN) {
    $values = functionReturningObject();
}
/*
if (null === $values) {
    throw new RuntimeException('Impossible error!');
}
*/
if (empty($values->property)) {
    ...
}

In the above case, sometimes explicitly testing the object for nullity or objectness is enough to remove the warning.

In some cases, the warning is actually correct:

$values = null;
switch ($flag) {
    case 0:
        $values = ...;
        break;
    case 1:
        $values = ...;
        break;
    case 2:
        $values = ...;
        break;
}

In the above case, the tool is warning you that in the unforeseen default case, however unlikely that might be, $values will be null.

CodePudding user response:

The function empty() doesn't care whether or not its parameter is defined or makes sense. empty returns false if $values is not defined or null, but also when it's not an object or when it is an object without the custom_field property. And if that property exists but it's not an array it also returns false. If it is an array but doesn't have the key section it again returns false.

PhpStan shows this message because it thinks that $values is null. It's possible that this is correct, you would have to check the code to find where $value is defined/assigned. But since it is used in empty it will not cause runtime problems. If $values is always null then the check just makes your code more complex.

  •  Tags:  
  • php
  • Related