PHP 5.4+ से, आप object को instantiate करके method को एक ही expression में call कर सकते हैं - "method chaining" या "fluent interface" के लिए उपयोगी।
मूल सिंटैक्स (PHP 5.4+)
// Parentheses आवश्यक हैं $result = (new MyClass())->myMethod(); // Arguments के साथ $result = (new MyClass($arg1, $arg2))->myMethod($arg3);
पूर्ण उदाहरण
<?php
class Calculator {
private $value;
public function __construct($initial = 0) {
$this->value = $initial;
}
public function add($n) {
$this->value += $n;
return $this; // Chaining के लिए $this return करें
}
public function multiply($n) {
$this->value *= $n;
return $this;
}
public function getResult() {
return $this->value;
}
}
// Method chaining - एक ही line पर
$result = (new Calculator(10))
->add(5)
->multiply(2)
->getResult();
echo $result; // 30
// या बिना chaining के single call
echo (new Calculator(5))->add(3)->getResult(); // 8
Static Factory Methods के साथ
<?php
class User {
private $name;
private $email;
private function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public static function create($name, $email) {
return new self($name, $email);
}
public function greet() {
return "Hello, {$this->name}!";
}
}
// One-liner with factory
echo (User::create('अमित', 'amit@example.com'))->greet();
// Output: Hello, अमित!
Anonymous Classes (PHP 7+) के साथ
<?php
// Quick object creation
$logger = (new class {
public function log($msg) {
echo "[LOG] $msg\n";
}
})->log('Application started');
// Interface implementation
$handler = (new class implements Countable {
private $items = [];
public function add($item) { $this->items[] = $item; }
public function count() { return count($this->items); }
})->add('item1')->add('item2');
echo $handler->count(); // 2
व्यावहारिक उपयोग मामले
| पैटर्न | उदाहरण |
|---|---|
| Builder Pattern | (new QueryBuilder())->select('*')->from('users')->where('id', 1)->get() |
| DTO Creation | (new UserDTO())->setName('John')->setEmail('john@test.com') |
| Validation | (new Validator($data))->required('email')->email('email')->validate() |
| Configuration | (new Config())->set('debug', true)->set('env', 'prod') |
सीमाएं
- केवल PHP 5.4+ में काम करता है
- Constructor arguments के लिए parentheses आवश्यक:
(new Class($arg)) - Method को
$thisreturn करना चाहिए chaining के लिए - Debugging थोड़ा कठिन हो सकता है (stack traces में anonymous points)