PHP

PHP

Made by DeepSource

Invalid usage of class constant fetch expression PHP-W1006

Bug risk
Critical

The class constant you're trying to access isn't valid and could lead to runtime errors.

This issue is raised for the following cases:

  • Trying to access a class that doesn't exist.
  • Using self/static/parent outside a class.
  • Trying to access a class constant defined in a class that is not in scope.
  • Accessing a private/undefined constant in a class.
  • Trying to access the ::class constant on a dynamic string.
  • Using the ::class constant on an expression in PHP < 8.0. Accessing this value on an expression is supported only in PHP 8.0 and later.

Any of the operations mentioned above would result in a fatal runtime error, and may potentially crash the application. Avoid performing such operations.

Bad practice

class Version
{
    private const PHP_74 = 70400;

    public const PHP_80 = 80000;
}

echo PhpVersion::PHP_80; // invalid: class "PhpVersion" doesn't exist

echo self::PHP_74; // invalid: cannot use "self" outside of a class

echo Version::PHP_56; // invalid: class constant "PHP_56" is undefined

$version = new Version;
echo $version::class; // note: this will only work on PHP 8.0 or later

Recommended

class Version
{
    public const PHP_56 = 50600;

    public const PHP_74 = 70400;

    public const PHP_80 = 80000;
}

// valid: make sure class exists and constant is defined
echo Version::PHP_80;

// valid: make sure to define constant that is being accessed
echo Version::PHP_56;

// valid: change visibility to public, or implement a getter method to retrieve the private constant or properties
echo Version::PHP_74;

References