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


Writing an universal fill method for several classes in PHP 5.3

例如,我有两个类:

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中做到这一点?

使用抽象类并让共享功能的类扩展

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;
}