[英]php automated setter and getter
I'm trying to implement some automated getter and setter for php objects. 我正在尝试为php对象实现一些自动getter和setter。
My target is to automatically have for each properties the methods getProperty()
and setProperty(value)
, that way if the method is not implemented for a property the script will simply set or get the value. 我的目标是为每个属性自动拥有方法
getProperty()
和setProperty(value)
,这样如果没有为脚本将设置或获取值的属性实现该方法。
An example, to make myself clear: 一个例子,让自己清楚:
class Foo {
public $Bar;
}
$A = new A();
$A->setBar("bar");
$A->getBar(); // -> output "bar"
or 要么
class Foo {
public $Bar;
public function setBar($bar) { $Bar = $bar; }
public function getBar($bar) { return 'the value is: ' . $bar; }
}
$A = new A();
$A->setBar("bar");
$A->getBar(); // -> output "the value is: bar"
Any idea/hints on how to accomplish this? 关于如何实现这一点的任何想法/提示?
If you want to simulate the getXy
and setXy
functions for arbitrary properties, then use the magic __call
wrapper: 如果要为任意属性模拟
getXy
和setXy
函数,请使用magic __call
包装器:
function __call($method, $params) {
$var = lcfirst(substr($method, 3));
if (strncasecmp($method, "get", 3) === 0) {
return $this->$var;
}
if (strncasecmp($method, "set", 3) === 0) {
$this->$var = $params[0];
}
}
This would be a good opportunity to do something useful for once, by adding a typemap or anything. 通过添加类型映射或任何东西,这将是一次有用的事情的好机会。 Otherwise eschewing getters and setters alltogether might be advisable.
否则,最好避开吸气剂和制定者可能是明智之举。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.