在PHP 5.3中为几个类编写通用填充方法

时间:2013-06-24 09:04:30

标签: php inheritance

例如,我有两个类:

class A {
  protected $x, $y;
}

class B {
  protected $x, $z;
}

在每个中我需要一个方法来填充数组中的数据。因此,既然可以编写通用填充符,我想编写一次这段代码。

在5.4中我相信特征可以写出像

这样的东西
protected function fill(array $row) {
  foreach ($row as $key => $value) {
    $this->$$key = $value;
  }
}

然后使用它。

但我怎么在5.3中做到这一点?

1 个答案:

答案 0 :(得分:2)

使用抽象类并具有共享功能的类

abstract class Base
{
    protected function fill(array $row) {
        foreach ($row as $key => $value) {
            $this->{$key} = $value;
        }
    }
}

class A extends Base {
    protected $x, $y;
}

class B extends Base {
    protected $x, $z;
}