Skip to content

Instantly share code, notes, and snippets.

@devmsh
Last active September 6, 2016 10:44
Show Gist options
  • Save devmsh/083c80b5671e79a05147b3b60b027dcc to your computer and use it in GitHub Desktop.
Save devmsh/083c80b5671e79a05147b3b60b027dcc to your computer and use it in GitHub Desktop.
PHP Magical Setter and Getter
<?php
// once you add the magical setter and getter
// you can can access any private fields as usual
// but you can also develop custom setter and getter if you want
$user = new MagicUser();
$user->username = "test";
$user->password = "pass";
echo $user->username; // will print Test not test.
// magical setter and getter
class MagicUser{
private $username;
private $password;
public function setUsername($username){
$this->username = ucfirst($username);
}
public function __set($name , $value){
$setter = 'set'.ucfirst($name);
if(method_exists($this,$setter)){
$this->$setter($value);
}else{
$this->$name = $value;
}
}
public function __get($name){
$getter = 'get'.ucfirst($name);
if(method_exists($this,$getter)){
return $this->$getter();
}else{
return $this->$name;
}
}
}
<?php
// without magical setter and getter
// you forced to develop setter and getter methods for each private field
$user = new User();
$user->setUsername("Mohammed");
echo $user->getUsername();
// regular setter and getter
class User{
private $username;
private $password;
public function setUsername($username){
$this->username = $username;
}
public function getUsername(){
return $this->username;
}
}
@mawadameshal
Copy link

mawadameshal commented Sep 5, 2016

in classmagicUser should be setUsername() method in the class ??

if we want to set/get the password we put it in the same method __set()/__get() ??

@devmsh
Copy link
Author

devmsh commented Sep 5, 2016

As you can see, I only add setUsername because I need to use ucfirst method or write any custom setter logic, but I did not add getUsername, setPassword or getPassword and I still can access these private method without any problem.

This way, I have the flexibility to add the setter and getter only and only if I have custom logic for setting or getting private field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment