Last active
September 6, 2016 10:44
-
-
Save devmsh/083c80b5671e79a05147b3b60b027dcc to your computer and use it in GitHub Desktop.
PHP Magical Setter and Getter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
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
in class
magicUser
should besetUsername()
method in the class ??if we want to set/get the
password
we put it in the same method__set()
/__get()
??