我有这样的例子类修改阵列嵌套类
Class RealUrlConfig
{
private $domains = [];
public function addDomain($host, $root_id)
{
$this->domains[] = [
'host' => $host,
'rootpage_id' => $root_id,
];
return $this; // <-- I added this
}
public function removeDomain($host)
{
foreach ($this->domains as $key => $item) {
if ($item['host'] == $host) {
unset($this->domains[$key]);
}
}
}
public function getDomains()
{
return $this->domains;
}
/**
* TODO: I need this
*/
public function addAlias($alias)
{
$last_modify = array_pop($this->domains);
$last_modify['alias'] = $alias;
$this->domains[] = $last_modify;
return $this;
}
}
现在我试图创建一个选项,添加别名主机。我可以提供原始主机名和别名并添加到阵列,但我想这样做没有原始主机 - 嵌套的方法,这样我可以这样执行它:
$url_config = new RealUrlConfig;
$url_config->addDomain('example.com', 1);
$url_config->addDomain('example2.com', 2)->addAlias('www.example2.com');
我加了return $this
到addDomain
方法,以便它返回对象,但我不明白,我怎么知道要修改哪个数组,因为我得到了整个对象。
我当然可以从domains数组中读取最后一个添加的域并对其进行修改,但我不太确定这是否正确。
只是为了解,为什么没有一个类域(与主机,rootpage_id和别名),然后在这个类中的addDomain做一个新的域,并返回新创建的域,而不是RealUrlConfig? –
@DoktorOSwaldo在返回数组时,我不能再作为对象的一部分进行修改,可以吗? – Peon
bcmcfc的答案正是我所推荐的。如果返回数组,则可以修改返回的数组,只需将其作为参考返回即可。但是一个数组没有函数addAlias。 –