5

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.

balping
  • 7,518
  • 3
  • 21
  • 35
  • 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. – PeeHaa Jun 11 '16 at 16:23
  • https://3v4l.org/mcKc7 – PeeHaa Jun 11 '16 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 – balping Jun 11 '16 at 16:44

1 Answers1

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;
balping
  • 7,518
  • 3
  • 21
  • 35
  • Why can't you just do `$myclass = new class { public $a; };`? – PeeHaa Jun 11 '16 at 17:08
  • @PeeHaa Because I'd like to use named constructors like: `$myobject = $myclass::fromString('abc')` where `fromString` returns a new instance – balping Jun 11 '16 at 17:40
  • 1
    This workaround simply creates an instance and then get the class from this instance. So it is not « without instance ». – Skrol29 Mar 05 '21 at 16:47