
因此,我正在適應木偶中的不可變變量,現在正在尋找一些建議,或者澄清我是否已經走在正確的軌道上。
我有一個想要同步的目錄,但可能有其中的許多子目錄。所以我想建立一個由一個或多個路徑組成的陣列來傳遞給遞歸文件資源。理想情況下,我會有這樣的東西
$paths = ['fist/path'] # assume this is provided via class parameter
# this should work, since it's only overriding what was provided from higher scope
if($condition) {
$paths += 'second/path'
}
# this won't fly, since $paths has already been set once locally
if($another_condition) {
$paths += 'third/path'
}
但我不能這樣做,對吧,因為變數是不可變的。到目前為止,我想出的「最佳」方法是這樣的
$paths = ['fist/path']
if($condition) {
$condition_1_path = ['second/path']
} else {
$condition_1_path = []
}
if($another_condition) {
$condition_2_path = ['third/path']
} else {
$condition_2_path = []
}
$paths = concat($paths, $condition_1_path, $condition_2_path)
我不確定是否連接如果為其參數之一提供了空數組,則會從結果中省略一個條目,但一旦我弄清楚如何載入 stdlib。
不管怎樣,看看這段程式碼,對我來說,它實在是太可怕了。有沒有更乾淨的方法可以做這樣的事情?
答案1
雖然很醜,但我就是這麼做的。
if($condition) {
$condition_1_path = 'first/path'
} else {
$condition_1_path = ''
}
if($another_condition) {
$condition_2_path = 'second/path'
} else {
$condition_2_path = ''
}
# split into array based on whitespace
$mylistofpaths = split("$condition_1_path $condition_2_path", '\s+')