gpt4 book ai didi

php - 合并后代对象的数组属性

转载 作者:可可西里 更新时间:2023-11-01 00:02:50 24 4
gpt4 key购买 nike

我有以下类层次结构,如下面的复制脚本所示:

<?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 值,则合并/覆盖。

问:我该怎么做?

我尝试过使用 array_merge() 但在非静态模式下,这些变量只会覆盖它们自己。有没有办法在没有static(后期静态绑定(bind))的情况下实现类树的合并效果?

最佳答案

与其声明一个 $config 属性,不如在构造函数中声明一个带有您要更改的值的属性,最好将这些值声明为默认值。 Orangepill 的回答中也描述了这一点:

class A
{
public $config;

private $defaults = array(
'param1' => 1,
'param2' => 2,
);

public function __construct(array $config = array())
{
$this->config = (object)($config + $this->defaults);
}
}

那里有一些曲折;通过将 $config 构造函数参数的默认值声明为空数组,您可以使用 array operators 简化代码就像我上面做的那样。 $config 中未定义的键由 $this->defaults 填充。

扩展类看起来非常相似:

class B extends A
{
private $defaults = array(
'param3' => 1
);

public function __construct(array $config = array())
{
parent::__construct($config + $this->defaults);
}
}

关于php - 合并后代对象的数组属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17802818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com