I regularly create a class that has a few private variables. When an instance of this class is set, it should be possible to fill all variables of the class with getters and setters.
Is there an easy way to do this without having to type all these setters and getters for each variable on creation of the class?
now i have to type this for each var in the class
public function setVar($var){
$this->var = $var;
}
and
public function getVar(){
return $this->var;
}
We now use RegExp, but i don't know if this is the easiest way... We use Eclipse as environment, so perhaps there are some usefull plugins?
With Eclipse go to Preferences -> PHP -> Editor -> Templates -> New and use something like this:
/**
* Method to get the ${PropertyName}
*
* @return ${ReturnType} return the ${PropertyName}.
*
* @since __DEPLOY_VERSION__
*/
public function get${MethodName}() {
return $$this->${PropertyName};
}
/**
* Method to set the ${PropertyName}
*
* @return boolean True on success and false on failed case
*
* @since __DEPLOY_VERSION__
*/
public function set${MethodName}($$value) {
$$this->${PropertyName} = $$value;
}
To use the template type its name and press ctrl+space - a context menu should also automatically appear when you type the name.
Have you looked at the __set and __get methods? Don't know if this is what you mean but the are automatically called whenever a class member is SET or Retrieved/Fetched/Accessed.
Zend Studio has a feature of automatic getter/setter generation.
I think the best way is to use the __set and __get with some string functions, Here let me show you.
class UserProfile
{
public function __get($key)
{
if(isset($this->$key))
{
return $this->$key;
}
}
public function __set($key,$val)
{
$this->cahnge($key,$val);
}
public function __call($key,$params)
{
if(substr("set",$key))
{
//Update
}elseif(substr("get",$key))
{
//return
}
//Else Blah
}
private function change($key,$val)
{
if(isset($this->$key))
{
$this->$key = $val;
}
}
}
the __call() method will allow you to set with functions such as
$profile->setUsername('Robert Pitt');
as long as you substr
the set/get and check for the rest of the string as a value of the class :)
another example
public function __call($method,$params = array())
{
if(isset($params[0]) && is_string($params[0]))
{
$this->$method = $params[0];
}
}
//....
$profile->username('Robert Pitt');
Theres more work to be done here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With