7

Is there a way of declaring an anonymous class that has no instance?

I'd like to do something like this:

$myclass = (class {
    public $a;
})::class;

$myobject = new $myclass;

This is something you can do with named classes, but the above code throws a syntax error.

3
  • The error you get tells you what is wrong. Once you fixed that you will get the error telling you that no, what you want is not possible. Fatal error: Dynamic class names are not allowed in compile-time ::class fetch in neither would it make that much sense. Commented Jun 11, 2016 at 16:23
  • 3v4l.org/mcKc7 Commented Jun 11, 2016 at 16:23
  • @PeeHaa Thanks. It would make sense for me, I'd like to test named constructors on subclasses of an abstract class. I'd like to make many different subclasses and I wouldn't like to pollute my tests file with them Commented Jun 11, 2016 at 16:44

1 Answer 1

6

Finally, I was able to make a workaround thanks to this comment at php.net

$myclass = get_class(new class {
    public $a;
});

$myobject = new $myclass;
Sign up to request clarification or add additional context in comments.

3 Comments

Why can't you just do $myclass = new class { public $a; };?
@PeeHaa Because I'd like to use named constructors like: $myobject = $myclass::fromString('abc') where fromString returns a new instance
This workaround simply creates an instance and then get the class from this instance. So it is not « without instance ».

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.