在PHP5.3中为几个类编写通用填充方法
例如,我有两门课:在PHP5.3中为几个类编写通用填充方法,php,inheritance,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 =
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;
}
公共基类不是一个选项?所以在这两个类中创建一个参数化构造函数…尝试将
$this->$$key
更改为$this->{$key}
@Sverri这些都是相同的东西。@complex857可能这只是我,但当我使用基类时,它会在该基类中搜索变量,而不是在孩子中。我尝试过这一点,但由于我在这里使用$this->,所以我假设它在父对象中查找变量。因此,对于这样的测试:使用$this->{$key}=$value
表单,变量在这里不起作用(可能是php解析器的怪癖,我不确定)。