Skip to content

Instantly share code, notes, and snippets.

@dominikzogg
Last active August 29, 2015 14:06
Show Gist options
  • Save dominikzogg/520e6b782fbf20cd6fe6 to your computer and use it in GitHub Desktop.
Save dominikzogg/520e6b782fbf20cd6fe6 to your computer and use it in GitHub Desktop.
accessor sample
<?php
/**
* Class Test
* @method $this setVar1(string $var1)
* @method $this getVar1()
* @method string getVar2()
*/
class Test
{
use AccessorTrait;
/**
* @var string
*/
protected $var1;
/**
* @var string
*/
protected $var2;
/**
* @param string $var2
* @return $this
*/
public function setVar2($var2)
{
$this->var2 = $var2;
return $this;
}
}
trait AccessorTrait
{
/**
* @param string $name
* @param array $arguments
*/
final public function __call($name, array $arguments = array())
{
$prefix = substr($name, 0, 3);
$variable = lcfirst(substr($name, 3));
if(property_exists(get_class($this), $variable)) {
if($prefix === 'set') {
if(count($arguments) !== 1) {
throw new \InvalidArgumentException("Magic setters need one argument!");
}
$this->$variable = $arguments[0];
return $this;
} elseif($prefix === 'get') {
if(count($arguments) !== 0) {
throw new \InvalidArgumentException("Magic getters need no argument!");
}
return $this->$variable;
}
}
throw new \InvalidArgumentException("Method does not exists!");
}
}
$test = new Test();
$test
->setVar1('var1')
->setVar2('var2')
;
$test->setVar1('var1');
$test->setVar2('var2');
var_dump($test->getVar1());
var_dump($test->getVar2());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment