-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?

3
  • 4
    new class creates an object. Commented Dec 17, 2020 at 1: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. Commented Dec 17, 2020 at 1: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? Commented Dec 17, 2020 at 9:39

1 Answer 1

5

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
    };
Sign up to request clarification or add additional context in comments.

3 Comments

Do I understand correctly that there's no way to create a class variable?
Checkout this resource: stackoverflow.com/questions/534159/… . Anyways, I'd use factory design pattern instead
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){}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.