Search code examples
phpoopencapsulation

Appropriate use case of __get in daily life programming


I am in learning phase of OOP and PHP. Below is how i implemented __get method. It is working fine but i don't understand why to use it. Since in my example i set the property to protected deliberately so that i can't be accessed via outside class. Then what is the purpose of __get then ?

class Magic {
    protected $name = 'John';
    public $age = 26;
    public $new_name;

    public function __get($key){
        $this->new_name = $key;
    }

    public function get_new_name(){
        return $this->new_name. " is my friend";
    }
}

$person = new Magic();
$person->Alan;
echo $person->get_new_name();

Solution

  • There is no valid reason I would have thought of that you would use __get() with a protected string, protected arrays would be useful, but not strings. The example you provided works, but it isn't going to be the best code for others to understand or for use with IDEs (code editors).

    Since you don't seem to understand what I was saying, here is an example of a quick database script.

    Let's say you want to insert a row in the database using an ORM-like class. You would do something like:

    Class Person {
      protected $fields = array();
      public function setField($name, $value) {
        $this->fields[$name] = $value;
      }
      public function getField($name) {
        return $this->fields[$name];
      }
      public function save() {
        Database::insert($table, $fields);  // Generic function to insert the row, don't worry about this.
      }
    }
    

    Now in this instance you could do:

    $person = new Person();
    $person->setField('name', 'Bob');
    $person->setField('age', '30');
    $person->save();
    
    echo $person->getField('name'); // Echoes Bob
    

    Overloading

    Now to change this, we could use overloading with __set() instead of setField() and __get() instead of getField():

    Class Person {
      protected $fields = array();
      public function __set($name, $value) {
        $this->fields[$name] = $value;
      }
      public function __get($name) {
       return $this->fields[$name];
      }
      public function save() {
        Database::insert($table, $fields);
      }
    }
    

    Now in this instance you could do:

    $person = new Person();
    $person->name =  'Bob';
    $person->age = '30';
    $person->save();
    
    echo $person->name; // Echoes Bob
    

    Hopefully this gives you an easy example of how overloading can work. We don't want to declare the properties $name and $age because we want to use those properties to build the $fields array which is later used in the insert.