PHP 7+ में Anonymous Classes का उपयोग करके on-the-fly objects create करना।
मूल Syntax (PHP 7+)
<?php
// Simple anonymous object
$obj = new class {
public $name = 'Anonymous';
public function greet() {
return "Hello, {$this->name}!";
}
};
echo $obj->greet(); // Hello, Anonymous!
Parent Class Extend करना
<?php
class BaseModel {
protected $id;
protected $createdAt;
public function __construct($id) {
$this->id = $id;
$this->createdAt = new DateTime();
}
public function getId() { return $this->id; }
public function getCreatedAt() { return $this->createdAt; }
}
// Anonymous class extending BaseModel
$user = new class(123) extends BaseModel {
public $name;
public $email;
public function __construct($id) {
parent::__construct($id);
}
public function getFullInfo() {
return "User {$this->name} ({$this->email}) - ID: {$this->getId()}";
}
};
$user->name = 'अमित';
$user->email = 'amit@example.com';
echo $user->getFullInfo();
Interface Implement करना
<?php
interface LoggerInterface {
public function log(string $message): void;
public function getLogs(): array;
}
// Anonymous class implementing interface
$logger = new class implements LoggerInterface {
private $logs = [];
public function log(string $message): void {
$this->logs[] = "[" . date('H:i:s') . "] $message";
}
public function getLogs(): array {
return $this->logs;
}
};
$logger->log('Application started');
$logger->log('User logged in');
print_r($logger->getLogs());
Constructor Arguments Pass करना
<?php
$handler = new class('api_key_123', 'https://api.example.com') {
private $apiKey;
private $baseUrl;
public function __construct(string $apiKey, string $baseUrl) {
$this->apiKey = $apiKey;
$this->baseUrl = $baseUrl;
}
public function request(string $endpoint): array {
// Simulate API call
return ['status' => 'ok', 'endpoint' => $endpoint];
}
};
$result = $handler->request('/users');
Use Cases
| Use Case | Example |
|---|---|
| Test Doubles / Mocks | Testing में quick mock objects |
| One-off implementations | Single-use interface implementations |
| Configuration objects | Fluent builders |
| Event handlers | Inline callbacks with state |
| DTOs with behavior | Data + methods together |
Limitations
- Named classes की तरह reusable नहीं
- Type hints में उपयोग नहीं कर सकते (केवल
objectया interface) - Serialization issues हो सकते हैं
- Reflection में anonymous class name unpredictable होता है
Comparison: Anonymous Class vs Closure
<?php
// Closure - single function, no state (or use &use)
$greeter = function($name) {
return "Hello, $name!";
};
// Anonymous class - multiple methods, state, implements interfaces
$greeter = new class {
private $greeting = 'Hello';
public function setGreeting($g) { $this->greeting = $g; }
public function greet($name) { return "{$this->greeting}, $name!"; }
public function greetFormal($name) { return "Good day, $name."; }
};
// जब state और multiple methods चाहिए → anonymous class
// जब simple callback चाहिए → closure