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

<?php
class 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 ParentClass to demonstrate inheritance in an anonymous class variable.
  • Line 9: We create an anonymous class object by extending the ParentClass.
  • Line 14: We call the helloWorld method defined in the ParentClass.

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.

<?php
class ParentClass{
public function __construct($foo){
echo "Hello $foo\n";
}
}
interface AnInterface{
// Interface method can only be public and without content
public 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 above
use ATrait;
public function __construct($foo){
parent::__construct($foo);
}
// implementing method declared in interface
public 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 $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

Copyright ©2025 Educative, Inc. All rights reserved