What are magic methods in PHP? Explain __get, __set, __call, and __toString. PHP में magic methods क्या हैं? __get, __set, __call और __toString समझाएं।
Magic methods are special methods prefixed with double underscores that PHP calls automatically in specific situations, without you calling them directly.
| Method | Triggered when |
|---|---|
| __get($name) | Reading an inaccessible or undefined property |
| __set($name, $value) | Writing to an inaccessible or undefined property |
| __call($name, $args) | Calling an inaccessible or undefined method |
| __toString() | Object is used in a string context, e.g. echo $obj |
| __invoke() | Object is called like a function, e.g. $obj() |
class Product {
private array $data = [];
public function __set($name, $value) { $this->data[$name] = $value; }
public function __get($name) { return $this->data[$name] ?? null; }
public function __toString(): string { return 'Product: ' . ($this->data['name'] ?? 'Unknown'); }
}
$p = new Product();
$p->name = 'Laptop'; // triggers __set
echo $p->name; // triggers __get
echo $p; // triggers __toStringInterview tip: Warn that overusing magic methods hurts IDE autocompletion and debuggability - use them for specific patterns like ORMs or DTOs, not as a default habit.
Magic methods खास methods हैं जिनके नाम double underscore से शुरू होते हैं, जिन्हें PHP खास स्थितियों में अपने आप call करता है, बिना आपके सीधे call किए।
| Method | कब trigger होता है |
|---|---|
| __get($name) | inaccessible या undefined property पढ़ते समय |
| __set($name, $value) | inaccessible या undefined property में लिखते समय |
| __call($name, $args) | inaccessible या undefined method call करते समय |
| __toString() | object को string context में इस्तेमाल करते समय, जैसे echo $obj |
| __invoke() | object को function की तरह call करते समय, जैसे $obj() |
class Product {
private array $data = [];
public function __set($name, $value) { $this->data[$name] = $value; }
public function __get($name) { return $this->data[$name] ?? null; }
public function __toString(): string { return 'Product: ' . ($this->data['name'] ?? 'Unknown'); }
}
$p = new Product();
$p->name = 'Laptop'; // __set trigger होता है
echo $p->name; // __get trigger होता है
echo $p; // __toString trigger होता हैइंटरव्यू टिप: बताएं magic methods का ज़्यादा इस्तेमाल IDE autocompletion और debuggability को नुकसान पहुंचाता है - इन्हें ORMs या DTOs जैसे specific patterns में इस्तेमाल करें, आदत के तौर पर नहीं।
Was this answer clear?