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:
Internally, an anonymous class is handled by generating a run-time random class name.
We can define an anonymous class in different ways. An anonymous class can implement and extend anything.
Let’s look at some examples.
<?phpinterface 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
.
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));