Last active
December 3, 2018 08:48
-
-
Save syrm/561d115857308a98bd4593bba50a48b1 to your computer and use it in GitHub Desktop.
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 | |
trait setterGetter | |
{ | |
private function resolveVariable() | |
{ | |
$method = debug_backtrace()[1]['function']; | |
$variable = strtolower(substr($method, 3)); | |
if ($variable === '') { | |
throw new RuntimeException(sprintf("Can't call %s::%s", __CLASS__, $method)); | |
} | |
return $variable; | |
} | |
public function get() | |
{ | |
$variable = $this->resolveVariable(); | |
return $this->$variable; | |
} | |
public function set($value) | |
{ | |
$variable = $this->resolveVariable(); | |
$this->$variable = $value; | |
return $this; | |
} | |
} | |
class Bouh { | |
use setterGetter { | |
get as getB; | |
set as setB; | |
get as getC; | |
set as setC; | |
} | |
private $b; | |
private $c; | |
} | |
$bouh = new Bouh(); | |
$bouh->setB("it's b"); | |
$bouh->setC("it's c"); | |
echo $bouh->getB() . PHP_EOL; | |
echo $bouh->getC() . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment