我有下面的类层次结构,这在下面再现脚本中所示:合并数组属性的对象
<?php
header('Content-Type: text/plain');
class A
{
public $config = array(
'param1' => 1,
'param2' => 2
);
public function __construct(array $config = null){
$this->config = (object)(empty($config) ? $this->config : array_merge($this->config, $config));
}
}
class B extends A
{
public $config = array(
'param3' => 1
);
public function __construct(array $config = null){
parent::__construct($config);
// other actions
}
}
$test = new B();
var_dump($test);
?>
输出:
object(B)#1 (1) {
["config"]=>
object(stdClass)#2 (1) {
["param3"]=>
int(1)
}
}
我想要的东西,是A::$config
不能被重写通过B::$config
。可能有很多来自B
的后代类别,我想要更改$config
,但如果匹配$config
值,则需要那些$config
值合并/覆盖,如果匹配所有父代的$config
值。
问:我该怎么做?
我试过使用array_merge()
,但在非静态模式下,这些变量只是自己重写。如果没有static
(后期静态绑定),是否有办法实现类树的合并效果?
适应你可能* *可以做到这一点有很多Reflection'和反省的',检查当前类,其母公司,母公司等和合并的阵列。请参阅http://php.net/reflectionclass。 – deceze
@deceze为它编写答案,以便将来为其他用户使用。 :) –
@deceze好吧,会有很多过热,不是吗? – BlitZ