← Back to PHP Course | Chapter 8: OOP | Lesson 11 of 14

PHP Magic Methods

Magic methods special hidden helpers हैं जिन्हें PHP कुछ moments पर automatically call करता है, किसी door जैसे जो आपके पास जाते ही अपने आप खुल जाए। इनके नाम दो underscores से शुरू होते हैं।
Syntax
php
class ClassName {
    function __construct() { }
    function __toString() { return "text"; }
    function __get($name) { }
    function __set($name, $value) { }
}

Magic Methods क्या हैं?

Magic methods special methods हैं जिन्हें PHP कुछ events के जवाब में automatically call करता है, हमेशा एक double underscore prefix के साथ, जैसे __construct(), __toString(), या __get()।

उदाहरण: What are Magic Methods?

php
<?php
// Define the class `User`
class User {
    // Define the constructor `__construct` with no parameters
    function __construct() {
        // Print "User created\n" to the output
        echo "User created\n";
    }
    // Define the magic method `__toString` with no parameters
    function __toString() {
        // Return `"User object"` from this function
        return "User object";
    }
}
// Create a new `User` instance, stored in `$user`
$user = new User();
// Print `$user` to the output
echo $user;
?>

Constructor और Destructor

__toString() किसी object को यह define करने देता है कि string context में इस्तेमाल होने पर, जैसे इसे सीधे echo करने पर, यह किस string में बदल जाए — इसके बिना, PHP किसी object को string में convert करने की कोशिश में एक fatal error raise करता है।

उदाहरण: The Constructor and Destructor

php
<?php
// Define the class `Money`
class Money {
    // Declare the private property `$amount`
    private $amount;
    // Define the constructor `__construct` taking `$amount`
    function __construct($amount) {
        $this->amount = $amount;
    }
    // Define the magic method `__toString` with no parameters
    function __toString() {
        // Return `"$" . number_format($this->amount, 2)` from this function
        return "$" . number_format($this->amount, 2);
    }
}
// Print `new Money(19.5)` to the output
echo new Money(19.5);
?>

Property Overloading (__get और __set)

__get() और __set() उन properties तक access intercept करते हैं जो exist नहीं करतीं या normally accessible नहीं हैं, आपको custom logic (जैसे validation या lazy loading) implement करने देते हुए जो तब चलता है जब भी code एक virtual property पढ़े या लिखे।

उदाहरण: Property Overloading (__get and __set)

php
<?php
// Define the class `Config`
class Config {
    // Declare the private property `$data`, set to `[]`
    private $data = [];
    // Define the magic method `__set` taking `$name`, `$value`
    function __set($name, $value) {
        $this->data[$name] = $value;
    }
    // Define the magic method `__get` taking `$name`
    function __get($name) {
        // Return `$this->data[$name] ?? null` from this function
        return $this->data[$name] ?? null;
    }
}
// Create a new `Config` instance, stored in `$config`
$config = new Config();
$config->theme = "dark";
// Print `$config->theme` to the output
echo $config->theme;
?>

Object से String (__toString)

__call() उन methods की calls intercept करता है जो object पर exist नहीं करते, जो है कि कई ORM libraries flexible, dynamic-looking method names implement कैसे करती हैं बिना literally सैकड़ों real methods define किए।

उदाहरण: Object to String (__toString)

php
<?php
// Define the class `Model`
class Model {
    // Define the magic method `__call` taking `$name`, `$args`
    function __call($name, $args) {
        // Print "Called method: $name\n" to the output
        echo "Called method: $name\n";
    }
}
// Create a new `Model` instance, stored in `$model`
$model = new Model();
$model->getName();
?>

Method Overloading (__call)

क्योंकि magic methods implicitly चलते हैं और किसी class की normal method list में visible नहीं होते, इन्हें overuse करना code को trace और debug करना मुश्किल बना सकता है — वे powerful हैं लेकिन genuinely अच्छी वजह वाले cases के लिए best reserved हैं।

उदाहरण: Method Overloading (__call)

php
<?php
// Define the class `Product`
class Product {
    // Declare the private property `$data`, set to `[]`
    private $data = [];
    // Define the magic method `__get` taking `$name`
    function __get($name) {
        // Print "Reading '$name' via magic method\n" to the output
        echo "Reading '$name' via magic method\n";
        // Return `$this->data[$name] ?? null` from this function
        return $this->data[$name] ?? null;
    }
}
// Create a new `Product` instance, stored in `$p`
$p = new Product();
// Print `$p->price` to the output
echo $p->price;
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि __get और __set सिर्फ inaccessible या missing properties के लिए चलते हैं।
  2. __toString से string के अलावा कुछ और return करना।
  3. PHP को इसे call करने पर भरोसा करने के बजाय किसी magic method को सीधे call करना।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.