Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
