我定期创建一个包含一些私有变量的类。设置此类的实例时,应该可以使用getter和setter填充该类的所有变量。
是否有一种简单的方法,而不必在创建类时为每个变量键入所有这些setter和getter?
现在我必须为类中的每个变量键入此名称
public function setVar($var){
$this->var = $var;
}
和
public function getVar(){
return $this->var;
}
我们现在使用RegExp,但是我不知道这是否是最简单的方法...我们使用Eclipse作为环境,所以也许有一些有用的插件?
使用Eclipse,转到“首选项”->“ PHP”->“编辑器”->“模板”->“新建”,并使用类似以下内容:
/**
* 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;
}
要使用模板,请输入其名称,然后按ctrl + space-在键入名称时,上下文菜单也会自动出现。
您是否看过__set和__get方法?不知道这是否是您的意思,但是只要对类成员进行SET或Retrieved / Fetched / Accessed就会自动调用。
Zend Studio具有自动生成getter / setter的功能。
我认为最好的方法是将__set和__get与某些字符串函数一起使用,这里让我展示给您。
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;
}
}
}
__call()方法将允许您使用诸如]之类的函数进行设置
[$profile->setUsername('Robert Pitt');
,只要您substr
设置/获取并检查字符串的其余部分作为类的值:)
另一个例子
public function __call($method,$params = array()) { if(isset($params[0]) && is_string($params[0])) { $this->$method = $params[0]; } } //.... $profile->username('Robert Pitt');
这里还有更多工作要做
也许更好的解决方法: