PHP

PHP

Made by DeepSource

Invalid class instantiation PHP-W1012

Bug risk
Critical

The class has been incorrectly instantiated, which would cause a runtime error.

This issue will be reported in the following cases:

  • The constructor is supplied with more than or fewer parameters than it requires.
  • The constructor is supplied with parameters of the wrong type.
  • The constructor is not public.
  • There is a typo in the class's name.
  • Instantiated class is not found.
  • You are attempting to instantiate an abstract class or interface. This is a forbidden operation.

This is not an exhaustive list of causes. Please refer to each occurrence's message for more details.

Bad practice

class Greet
{
    public function __construct(string $message) {}

    public function getInstance()
    {
        new self(); // invalid: "Greet" class's constructor invoked with 0 parameters, but 1 is required.
    }
}

$greet = new Greet(1); // invalid: Greet expects its first parameter to be a string, but it is given an int.
interface Admin {}

$admin = new Admin(); // invalid: cannot instantiate an interface.
abstract class User
{
    abstract public function getName();
}

$admin = new User(); // invalid: cannot instantiate an abstract class.

Recommended

class Greet
{
    public function __construct(string $message) {}

    public function getInstance()
    {
        new self('Hello');
    }
}

$greet = new Greet('Hi');

References