What is use of _get and _set methods in php

Object Oriented Programming

Posted on 18 Jun 15 by Vickey
  1126



_get method

_get method called when object try to read an inaccessible or unavailable property. This make a property that is not available.
For example in the class 'User' i have getdetails function in which i have defined 'name' 'email' and 'phone' but not defined 'dob'
so when i create an object and try to access dob then it will show a message that i gave in _get function for this property

class User{

  public function __construct() {
    $this->getdetails();
  }
  public function getdetails() {
    $this->name='vickey';
    $this->email='test@gmail.com';
    $this->phone='123456';
    return $this;
  }


  public function __get($field) {
      return $field.' field not exist';
  }
}
$tux = new User();
echo $tux->name; echo "
";
echo $tux->email; echo "
";
echo $tux->phone; echo "
";
echo $tux->dob; echo "
";

 

_set method

In set method we can set a new value for example in the below code i have email but i have set it by _set method

class User{

  public function __construct() {
    $this->getdetails();
  }
  public function getdetails() {
    $this->name='vickey';
    $this->email='test@gmail.com';
    $this->phone='123456';
    return $this;
  }


  public function __get($field) {
      return $field.' field not exist';
  }

  public function __set($field, $value) {

    if($field == 'email') {
      $this->email = 'We can not show you email';
    }
  }
}
$tux = new User();
echo $tux->name; echo "
";
echo $tux->email; echo "
";
echo $tux->phone; echo "
";
echo $tux->dob; echo "
";

 


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com