-1

I am trying to create an anonymous class which extends an abstract class.

$trainerEngineClass = new class extends \App\MemoryBoost\TrainerEngine {
    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?

Vega TV
  • 217
  • 2
  • 10
  • 4
    `new class` creates an object. – Don't Panic Dec 17 '20 at 01:34
  • 2
    Creating an anonymous class without also instantiating it would be entirely useless. How would you identify your nameless class in order to instantiate it? If you want a class, create one in the normal way. If you want the object, pass the prameters you have defined. –  Dec 17 '20 at 01:34
  • I've never heard the term *create* applied to class definition. Classes are defined, objects of classes are created. What is "create class*? What should it do? – astentx Dec 17 '20 at 09:39

1 Answers1

3

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 \App\MemoryBoost\TrainerEngine {
        public function __construct($user, $trainer) {
            parent::__construct($user, $trainer);
        }

        // Overriden abstract methods
    };
fluid undefined
  • 364
  • 2
  • 6
  • Do I understand correctly that there's no way to create a class variable? – Vega TV Dec 17 '20 at 01:42
  • 2
    Checkout this resource: https://stackoverflow.com/questions/534159/instantiate-a-class-from-a-variable-in-php . Anyways, I'd use factory design pattern instead – fluid undefined Dec 17 '20 at 01:45
  • The interesting thing is that PHP seems to not only *define* an anonymous class, but *instantiates* it as well. This doesn't work: `$c=new class(0){function __construct(DateTime$p){}}`. But this does: `$c=new class(new DateTime){function __construct(DateTime$p){}}` – aross Jun 22 '21 at 17:06