I am trying to create an anonymous class which extends an abstract class.
$trainerEngineClass = new class extends AppMemoryBoostTrainerEngine { public function __construct($user, $trainer) { parent::__construct($user, $trainer); } // Abstract method implementation here };
PHP shows an error:
Too few arguments to function class@anonymous::__construct(), 0 passed in TrainerController.php on line 74 and exactly 2 expected
I excepted that __construct
will not be called, but it seems that it called. I want to create a class, not an object of this class
What should I do to create a class object?
Advertisement
Answer
At the very end, you are instantiating a class, so, the constructor is been fired. Anonymous classes, as it’s mentioned in the documentation, are useful for creating single and uniques objects, not for creating a template.
The syntax for passing params through is:
$trainerEngineClass = new class($user, $trainer) extends AppMemoryBoostTrainerEngine { public function __construct($user, $trainer) { parent::__construct($user, $trainer); } // Overriden abstract methods };