Last active
November 23, 2018 05:31
-
-
Save amekusa/2e8bf2743927b92697b2c3652304c544 to your computer and use it in GitHub Desktop.
Dynamic getter/setter implementation for PHP
This file contains hidden or 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 | |
| /** | |
| * Example class | |
| */ | |
| class Dog { | |
| private $name, $breed, $age; | |
| public function __call($Fn, $Args) { | |
| $act = substr($Fn, 0, 3); | |
| if ($act == 'get') { // Getter | |
| $prop = lcfirst(substr($Fn, 3)); | |
| return $this->$prop; | |
| } else if ($act == 'set') { // Setter | |
| $prop = lcfirst(substr($Fn, 3)); | |
| if (isset($Args[0])) $this->$prop = $Args[0]; | |
| return $this; | |
| } | |
| return false; // No such method | |
| } | |
| } | |
| /** Demonstration **/ | |
| $dog = new Dog(); | |
| $dog->setName('Strax') | |
| ->setBreed('Poodle') | |
| ->setAge(3); | |
| echo $dog->getName(); // 'Strax' | |
| echo $dog->getBreed(); // 'Poodle' | |
| echo $dog->getAge(); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment