What is an anonymous class in PHP?

In PHP, an anonymous class is a useful way to implement a class without defining it.

These are available from PHP 5.3 onwards.

Anonymous classes are useful because:

  • They are not associated with a name.
  • They can be used as function parameters.

Internally, an anonymous class is handled by generating a run-time random class name.

How to define an anonymous class

We can define an anonymous class in different ways. An anonymous class can implement and extend anything.

Let’s look at some examples.

Example 1

<?php
interface MyInterface{}
$acl = new class implements MyInterface {
public function sayHello(){
echo "Hello!";
}
};
$acl->sayHello();

In this example, we created a class that implemented the interface MyInterface and called the method sayHello.

Example 2

In the following example, we will also define a constructor with these parameters.

Note that the name of the class will change every time we run the example.

<?php
$ac = new class("Educative") {
private $name;
public function __construct(string $name){
$this->name = $name;
}
public function sayHelloTo(){
echo "Hello, " . $this->name . "!\n";
}
};
$ac->sayHelloTo();
var_dump(get_class($ac));