PHP

PHP

Made by DeepSource

Bad argument passed to isset PHP-W1040

Anti-pattern
Major

isset is either used with an undefined variable or a variable that is known to be defined and non-null.

isset is used to check if a variable is considered "set"; it will return true if:

  • The variable's declaration is visible in the current scope
  • Its value is not null

Bad practice

class Greet
{
    public function getMessage($name = null)
    {
        $result = '';
        $defaultName = 'User';

        // $message is never defined, so this condition will evaluate to false
        if (isset($message)) {
            $result .= $message;
        }

        if (isset($name)) {
            $result .= ' ' . $name;
        } else {
            $result .= ' ' . $defaultName;
        }

        return $result;
    }
}
class Greet
{
    public function getMessage($message, $name = null)
    {
        $result = '';
        $defaultName = 'User';

        // $message is exists and non-nullable, so this condition will always evaluate to true
        if (isset($message)) {
            $result .= $message;
        }

        if (isset($name)) {
            $result .= ' ' . $name;
        } else {
            $result .= ' ' . $defaultName;
        }

        return $result;
    }
}

Recommended

If the variable was supposed to be defined, do so. Otherwise, get rid of the isset condition:

class Greet
{
    public function getMessage($name = null, $message = null)
    {
        $result = '';
        $defaultName = 'User';

        if (isset($message)) {
            $result .= $message;
        }

        if (isset($name)) {
            $result .= ' ' . $name;
        } else {
            $result .= ' ' . $defaultName;
        }

        return $result;
    }
}

Remove the isset usage if the variable is known be in scope and cannot be null:

class Greet
{
    public function getMessage($message, $name = null)
    {
        $result = '';
        $defaultName = 'User';

        $result .= $message;

        if (isset($name)) {
            $result .= ' ' . $name;
        } else {
            $result .= ' ' . $defaultName;
        }

        return $result;
    }
}

References