An anonymous is created when the code is used only once, and we do not need to refer it elsewhere. What if we need code that is already defined?
Not to worry! We can perform inheritance in anonymous classes as well. They are just like the standard classes, except the engine auto-generates their names.
Note: Read more on What is class Inheritance in PHP?
$obj = new class extends ParentClass
{
/* Class implementation */
};
Note: Abstract classes can also be extended similarly.
<?phpclass ParentClass{public function helloWorld(){echo "Hello $foo\n";}}// creating an object by defining an anonymous class$obj = new class extends ParentClass{/* Class implementation */};$obj->helloWorld();?>
ParentClass
to demonstrate inheritance in an anonymous class variable.ParentClass
.helloWorld
method defined in the ParentClass
.You can add arguments by using ()
in front of the keyword class
. You can also implement an interface
and use traits
in an anonymous class as well.
<?phpclass ParentClass{public function __construct($foo){echo "Hello $foo\n";}}interface AnInterface{// Interface method can only be public and without contentpublic function helloInterface();}trait ATrait{public function helloTrait(){echo "Hello Trait\n";}}// creating an object by defining an anonymous class$obj = new class("X") extends ParentClass implements AnInterface{// adding code of trait defined aboveuse ATrait;public function __construct($foo){parent::__construct($foo);}// implementing method declared in interfacepublic function helloInterface(){echo "Hello Interface\n";}/* Class implementation */};$obj->helloTrait();$obj->helloInterface();?>
Line 2: We define the content for the method declared in the interface.
Lines 2–6: We define a dummy class with a constructor that accepts $foo
as an argument and prints its value.
Lines 8–11: We define a dummy interface with the method helloInterface
.
Lines 12–16: We define a dummy trait with the method helloTrait
that prints Hello Trait
.
Line 19: We inherit code from ParentClass
and call its constructor on line 24.
Line 22: We horizontally inherit code from the trait to our class.
Line 34: We call the method helloTrait
defined in the ATrait
.
Line 35: We call the method helloInterface
declared in the AnInterface
.
Free Resources