seb*_*taz 8 php oop getter setter
我正在尝试为php对象实现一些自动getter和setter.
我的目标是自动为每个属性的方法getProperty()和setProperty(value),这样,如果没有为脚本只是设置一个属性来实现或获得的价值的方法.
一个例子,让自己清楚:
class Foo {
public $Bar;
}
$A = new A();
$A->setBar("bar");
$A->getBar(); // -> output "bar"
Run Code Online (Sandbox Code Playgroud)
要么
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"
Run Code Online (Sandbox Code Playgroud)
关于如何实现这一点的任何想法/提示?
mar*_*rio 24
如果要模拟任意属性的函数getXy和setXy函数,请使用魔术__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];
}
}
Run Code Online (Sandbox Code Playgroud)
通过添加类型映射或任何东西,这将是一次有用的事情的好机会.否则,最好避开吸气剂和制定者可能是明智之举.