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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As you can see, I only add
setUsername
because I need to useucfirst
method or write any custom setter logic, but I did not addgetUsername
,setPassword
orgetPassword
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.