Skip to content

Instantly share code, notes, and snippets.

@kpion
Created February 10, 2017 21:11
Show Gist options
  • Save kpion/5780722438bc0563f850b48705d8ac6e to your computer and use it in GitHub Desktop.
Save kpion/5780722438bc0563f850b48705d8ac6e to your computer and use it in GitHub Desktop.
<?php
/**
* Disclaimer - I am aware using __call to set things isn't anything new, once upon a time, I created an ORM class doing that, but this
* time I'd like to ask about using this approach actually everytime we need accessors like set/get.
*
* OK, so using accessors is a good practice. But quite boring, isn't it? Even with all this IDEs' support (menu code -> create accessors for me please).
*
* Why not use the __call magic method catching "get/set" methods?
*
* On a ocassion we indeed need a set/get function we can explicitly create one.
* Like in the example below.
* Issues: obviously slower, no ide code support
*/
class Blah {
protected $firstName;
protected $age;
protected $myFavDrink = 'Coffee';
//this will handle all these "set/get" accessors. Except the ones, we explicitly define.
public function __call($method, $args) {
//No checking for the right number of arguments or whatever. Just to make the code clean.
echo "$method called, via __call\n";
if(strpos($method,'set') === 0){
$propName = lcfirst(substr($method,3,strlen($method) - 3));
$this->{$propName} = $args[0];
}elseif(strpos($method,'get') === 0){
$propName = lcfirst(substr($method,3,strlen($method) - 3));
return $this->{$propName};
}else{
throw new Exception('oh oh oh');
}
}
//we don't want and need to create a set/get for $firstName or anything. But,
//we want to do something special when we do the "set" on "age"
public function setAge($age){
echo "setAge called, directly\n";
if(!is_numeric($age)){
//$this->error('oh oh oh');
};
$this->age = $age;
}
}
$b = new Blah();
//this will call the seAge method
$b->setAge('30');
//this will call the __call magic method
$b->setFirstName('Angelika');
echo "\n---result---\n\n";
var_dump($b);
////////////////////////////////
//Inheritance doesn't make any surprises afaik.
echo "\n---result of the Son---\n\n";
class BlahSon extends Blah{
protected $something;
}
$bs = new BlahSon();
$bs->setSomething("I'm something");
var_dump($bs);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment