🔴 Advanced · Lesson 25
Magic Methods
Magic Methods
What are Magic Methods?
Magic methods start with
__ (double underscore) and run automatically on certain events — like creating an object or accessing a missing property.Common Magic Methods
| Method | Runs When |
|---|---|
| __construct() | object is created |
| __destruct() | object is destroyed |
| __get($name) | reading an inaccessible property |
| __set($name,$val) | writing an inaccessible property |
| __toString() | object is used as a string |
| __call($name,$args) | calling an undefined method |
Example
class User {
private $data = [];
public function __get($key) { return $this->data[$key] ?? null; }
public function __set($key, $val) { $this->data[$key] = $val; }
public function __toString() { return "User object"; }
}
$u = new User();
$u->name = "Aman"; // calls __set
echo $u->name; // calls __get -> Aman
echo $u; // calls __toString -> User object
Summary
- Magic methods (__construct, __get, __set, __toString, __call) run automatically on events.
- Useful for dynamic properties and clean object behavior.
Magic Methods क्या हैं?
Magic methods
__ (double underscore) से शुरू होती हैं और कुछ events पर अपने आप चलती हैं — जैसे object बनाना या missing property access करना।Common Magic Methods
| Method | कब चलती है |
|---|---|
| __construct() | object बनने पर |
| __destruct() | object नष्ट होने पर |
| __get($name) | inaccessible property पढ़ने पर |
| __set($name,$val) | inaccessible property लिखने पर |
| __toString() | object को string की तरह use करने पर |
| __call($name,$args) | undefined method call करने पर |
Example
class User {
private $data = [];
public function __get($key) { return $this->data[$key] ?? null; }
public function __set($key, $val) { $this->data[$key] = $val; }
public function __toString() { return "User object"; }
}
$u = new User();
$u->name = "Aman"; // __set call
echo $u->name; // __get -> Aman
echo $u; // __toString -> User object
सारांश
- Magic methods (__construct, __get, __set, __toString, __call) events पर अपने आप चलती हैं।
- Dynamic properties और साफ object behavior के लिए उपयोगी।