use*_*951 1 php magic-methods mapper getter-setter
现在我有一个 BaseObject 可以对 DB 执行 ORM。我依靠私有 $data 和魔法 setter 和 getter 来创建带有一堆列的对象作为私有对象成员(动态)。在子类中,如果我想更改行为以设置单个对象成员,我必须覆盖父 setter 并查找键。我的问题是是否有更好的方法来做到这一点,我可以只覆盖单个对象成员而不是通过 __setter
映射到数据库并动态创建一堆私有参数的基本对象映射器
class Base
{
private $data = array();
public function __construct(){
//get columns info from db and do set
}
public function __set($key, $value){
$this->data[$key] = $value;
}
public function __get($key){
return isset($this->data[$key])? $this->data[$key] : null;
}
}
Run Code Online (Sandbox Code Playgroud)
和儿童班。现在要覆盖参数设置我必须这样做
class Child extends Base
{
public function __set($name, $value){
if($name == 'dog' && $value == 'chihuahua')
$this->dog = 'dog bark wolf wolf';
else if($name == 'cat' && $value == 'sand')
$this->cat = 'cat say meow meow';
...
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是有没有优雅的方法可以做到这一点,也许在儿童课上是这样的?
public function __set_dog($value)
$this->dog = 'dog bark wolf wolf';
public function __set_cat($value)
$this->cat = 'cat say meow meow';
Run Code Online (Sandbox Code Playgroud)
目标是做
$animal1 = new Animal();
$anmial1->dog = 'pit bull';
$anmial1->cat= 'sand';
$animal2 = new Animal();
$anmial1->dog = 'chihuahua';
$anmial1->cat= 'house cat';
Run Code Online (Sandbox Code Playgroud)
您可以动态检查是否存在传统命名的 getter/setter 方法并调用它而不是返回 $data 成员。下面是一个例子:
class Base {
public function __get($key) {
if (method_exists($this, $method = 'get' . ucfirst($key))) {
return $this->$method($key);
} else {
return isset($this->data[$key])? $this->data[$key] : null;
}
}
public function __set($key, $value) {
if (method_exists($this, $method = 'set' . ucfirst($key))) {
$this->$method($key, $value);
} else {
$this->data[$key] = $value;
}
}
}
class Animal extends Base {
protected $data = array('fish' => 'blublublub', 'dog' => 'woof', 'cat' => 'meow');
public function getDog() {
return 'dog bark wolf wolf';
}
public function getCat() {
return 'cat say meow meow';
}
}
$animal = new Animal();
echo $animal->fish; // "blublublub"
echo $animal->dog; // "dog bark wolf wolf"
echo $animal->cat; // "cat say meow meow"
Run Code Online (Sandbox Code Playgroud)