我有這樣的例子類修改陣列嵌套類
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。 –