Skip to content

Instantly share code, notes, and snippets.

@syrm
Last active December 3, 2018 08:48
Show Gist options
  • Save syrm/561d115857308a98bd4593bba50a48b1 to your computer and use it in GitHub Desktop.
Save syrm/561d115857308a98bd4593bba50a48b1 to your computer and use it in GitHub Desktop.
<?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