Inheritance in anonymous classes in PHP
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?
Syntax
$obj = new class extends ParentClass
{
/* Class implementation */
};
Note: Abstract classes can also be extended similarly.
Example 1
<?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();?>
Explanation
- Lines 2–6: We create a dummy class
ParentClassto demonstrate inheritance in an anonymous class variable. - Line 9: We create an anonymous class object by extending the
ParentClass. - Line 14: We call the
helloWorldmethod defined in theParentClass.
Example 2
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();?>
Explanation
-
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
$fooas 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
helloTraitthat printsHello Trait. -
Line 19: We inherit code from
ParentClassand call its constructor on line 24. -
Line 22: We horizontally inherit code from the trait to our class.
-
Line 34: We call the method
helloTraitdefined in theATrait. -
Line 35: We call the method
helloInterfacedeclared in theAnInterface.
Free Resources