Chi*_*dhe 3 php oop parent-child
我试图将抽象父类中的属性与子类中的相同属性合并。代码看起来有点像这样(除了在我的实现中,有问题的属性是一个数组,而不是一个整数):
abstract class A {
public $foo = 1;
function __construct() {
echo parent::$foo + $this->foo; # parent::$foo NOT correct
}
}
class B extends A {
public $foo = 2;
}
$obj = new B(); # Ideally should output 3
Run Code Online (Sandbox Code Playgroud)
现在我意识到构造函数中的 parent::$foo 在这里不会按预期工作,但是如何在不将值硬编码到构造函数中或在父类中创建附加属性的情况下合并属性值?
在父类的构造函数中,执行以下操作:
<?php
abstract class ParentClass {
protected $foo = array(
'bar' => 'Parent Value',
'baz' => 'Some Other Value',
);
public function __construct( ) {
$parent_vars = get_class_vars(__CLASS__);
$this->foo = array_merge($parent_vars['foo'], $this->foo);
}
public function put_foo( ) {
print_r($this->foo);
}
}
class ChildClass extends ParentClass {
protected $foo = array(
'bar' => 'Child Value',
);
}
$Instance = new ChildClass( );
$Instance->put_foo( );
// echos Array ( [bar] => Child Value [baz] => Some Other Value )
Run Code Online (Sandbox Code Playgroud)
基本上,魔术来自get_class_vars( )函数,它会返回在该特定类中设置的属性,而不管子类中设置的值如何。
如果您想使用该函数获取 ParentClass 值,您可以在 ParentClass 本身中执行以下任一操作:get_class_vars(__CLASS__)或get_class_vars(get_class( ))
如果您想获取 ChildClass 值,您可以从 ParentClass 或 ChildClass 中执行以下操作:get_class_vars(get_class($this))尽管这与仅访问相同$this->var_name(显然,这取决于变量范围)。
| 归档时间: |
|
| 查看次数: |
2645 次 |
| 最近记录: |