所以我正在适应傀儡中不可变的variables,现在正在寻找一些build议,或澄清我是否已经走上了正轨。
我有一个目录,我想要同步,但可能有一些子目录。 所以我想build立一个或多个path的数组传递给recursion的文件资源。 理想情况下,我会有这样的事情
$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' }
但我不能这样做,对,因为variables是不可变的。 到目前为止,我所提出的“最佳”方法就是这样的
$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)
我不确定concat是否会从结果中忽略一个条目,如果为它的一个参数提供了一个空数组,但是一旦我弄清楚如何获得stdlib ,就等待testing。
无论哪种方式,看这个代码,对我来说,这简直是丑陋的。 有没有更干净的方式来做这样的事情?
这是丑陋的,但我已经这样做了。
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+')