PHP

PHP

Made by DeepSource

Invalid static method call detected PHP-E1003

Bug risk
Critical

Invalid call to a static method. This would lead to a run time error.

This issue can be raised for any of the following cases:

  • There's a typo in either the method call or class name.
  • The class on which the static method is called:
    • might not exist
    • might not be a Class
    • has not been imported into this scope
  • The method you are trying to call is not a static method.
  • The method you are trying to call is a private static method from a parent class.

Bad practice

class Output
{
    public static function writeMagic()
    {
        echo 'Magic!';
    }

    public function print()
    {
        return self::writeMaagic(); // typo, writeMaagic() doesn't exist
    }
}
class Output
{
    public static function writeMagic()
    {
        echo 'Magic!';
    }

    public function print()
    {
        return self::writemagic(); // typo
    }
}
class PrettyLog
{
    public static function log($data): void
    {
    }
}

class Log
{
    public function print()
    {
        $logger = false;

        return $logger::log('Something'); // $logger is not a class
    }
}
function log() {
    self::log(); // self/static can only be resolved inside a class
};
class Output
{
    public function writeMagic()
    {
        echo 'Magic!';
    }

    public function print()
    {
        return self::writeMagic(); // writeMagic() is not a static method
    }
}
class SuperOutput
{
    private static function writeMagic()
    {
        echo 'Magic!';
    }
}

class Output extends SuperOutput
{
    public function print()
    {
        return static::writeMagic(); // writeMagic() is a private static method
    }
}

Recommended

class Output
{
    public static function writeMagic()
    {
        echo 'Magic!';
    }

    public function print()
    {
        return self::writeMagic();
    }
}
class PrettyLog
{
    public static function log($data): void
    {
    }
}

class Log
{
    public function print()
    {
        $logger = 'PrettyLog';

        return $logger::log('Something');
    }
}
function log() {
    PrettyLogger::log();
};
class SuperOutput
{
    protected static function writeMagic()
    {
        echo 'Magic!';
    }
}

class Output extends SuperOutput
{
    public function print()
    {
        return static::writeMagic();
    }
}

References