Skip to content

Instantly share code, notes, and snippets.

@amekusa
Last active November 23, 2018 05:31
Show Gist options
  • Select an option

  • Save amekusa/2e8bf2743927b92697b2c3652304c544 to your computer and use it in GitHub Desktop.

Select an option

Save amekusa/2e8bf2743927b92697b2c3652304c544 to your computer and use it in GitHub Desktop.
Dynamic getter/setter implementation for PHP
<?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