Creating anonymous objects in PHP

Starting from PHP 7, you can create anonymous classes without explicitly defining a class name. Anonymous classes are useful for creating one−time objects, implementing interfaces on the fly, or extending existing classes temporarily.

Basic Anonymous Class

Here's how to create a simple anonymous class ?

<?php
$obj = new class {
    public $name = "Anonymous Object";
    
    public function getMessage() {
        return "Hello from " . $this->name;
    }
};

echo $obj->getMessage();
echo "<br>";
echo "Object class: " . get_class($obj);
?>
Hello from Anonymous Object
Object class: class@anonymous

Extending a Parent Class

Anonymous classes can extend existing classes ?

<?php
class ParentClass {
    protected $value = "Parent";
    
    public function getInfo() {
        return "From parent: " . $this->value;
    }
}

$obj = new class extends ParentClass {
    public function getInfo() {
        return "From anonymous child: " . $this->value;
    }
};

echo $obj->getInfo();
echo "<br>";
echo "Is instance of ParentClass? ";
var_dump($obj instanceof ParentClass);
?>
From anonymous child: Parent
Is instance of ParentClass? bool(true)

Implementing Interfaces

Anonymous classes can implement interfaces for specific behaviors ?

<?php
interface Drawable {
    public function draw();
}

$shape = new class implements Drawable {
    public function draw() {
        return "Drawing an anonymous shape";
    }
};

echo $shape->draw();
echo "<br>";
echo "Implements Drawable? ";
var_dump($shape instanceof Drawable);
?>
Drawing an anonymous shape
Implements Drawable? bool(true)

Constructor Parameters

Anonymous classes can accept constructor parameters ?

<?php
$calculator = new class(10, 5) {
    private $a, $b;
    
    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }
    
    public function add() {
        return $this->a + $this->b;
    }
    
    public function multiply() {
        return $this->a * $this->b;
    }
};

echo "Addition: " . $calculator->add();
echo "<br>";
echo "Multiplication: " . $calculator->multiply();
?>
Addition: 15
Multiplication: 50

Conclusion

Anonymous classes in PHP provide flexibility for creating objects without defining named classes. They're ideal for one−time use cases, implementing interfaces dynamically, or extending classes temporarily while maintaining clean, readable code.

Updated on: 2026-03-15T08:24:57+05:30

664 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements