PHP

PHP

Made by DeepSource

Method is called but not defined PHP-E1002

Bug risk
Critical

The method you are trying to call is not defined, which can result in a fatal error.

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

  • There's a spelling mistake in the method call.
  • The method is not defined in either the class or its ancestors.
  • You are trying to call a private method from a parent class.
  • You are attempting to access an improperly instantiated object or an undefined variable.
  • You are trying to use the return value of a method that returns void.

Bad practice

class User
{
    public function printName()
    {
        echo $this->getName(); // getName() doesn't exist.
    }
}
class User
{
    private function getName()
    {
        return 'John Doe';
    }
}

class Admin extends User
{
    public function printName()
    {
        echo $this->getName(); // `getName()` is private
    }
}
class Admin
{
    public function printName()
    {
        $user = new User(); // class `User` doesn't exist
        echo $user->getName();
    }
}
class User
{
    private $name;

    public function setName()
    {
        $this->name = 'Anonymous';
    }

    public function printName()
    {
        $name = $this->setName(); // the "setName" method doesn't return anything

        echo $name; // this will print nothing, because $name is NULL
    }
}

Recommended

class User
{
    public function printName()
    {
        echo $this->getName();
    }

    public function getName()
    {
        return 'John Doe';
    }
}
class User
{
    protected function getName()
    {
        return 'John Doe';
    }
}

class Admin extends User
{
    public function printName()
    {
        echo $this->getName();
    }
}
class User
{
    public function getName()
    {
        return 'John Doe';
    }
}

class Admin
{
    public function printName()
    {
        $user = new User();
        echo $user->getName();
    }
}

References