如何在PHP中命名稍微不同的方法,使其表现得像ruby";(砰)


How to name slightly different methods in PHP so it behaves like ruby "!" (bang)

我一直在思考如何应对这种情况:

以散列为例:

hash  = {'a' => 'b', 'c' => 'd'}
other = {'a' => 'd'}
hash.merge(other)  # returns a new hash
hash.merge!(other) # modifies hash

您将如何在php中处理此问题?

$hash  = new Hash(array( 'a' => 'b', 'c' => 'd' ));
$other = new Hash(array('a' => 'd'));

选项参数:

public function merge($other, array $options = array('mutate' => false))
{
}
// or
public function merge($other, $mutate = false)
{
}

或者可能有两个不同的方法名称:

public function merge($other)
{
}
public function mergeIntoSelf($other)
{
}

我有点喜欢"options-param"方法,但如果该方法实际上接收到另一个可选的param(如ruby中的param),那该怎么办?它是一个修饰符回调。

$hash->merge($other, function ($key, $originalValue, $otherValue) {
    if ($key === 'foo') {
        return $originalValue;
    }
    return $otherValue;
}, array('mutate' => true));

回调选项可能是第三个,而不是第二个,但我不喜欢这样。我也不喜欢检查参数并试图找出什么是什么的想法。他们的医生块变得毛茸茸的。

因此,我想听听你对如何处理这一问题的看法。

提前谢谢。

您可以在函数名处使用&符号,但这不是一个好的单独符号。我只想给出一个可能的想法:

$a = array( 'a' => 'b', 'c' => 'd' );
$b = array('a' => 'd');
function mergeArray(& $a,$b) {
    return $a = array_merge($a,$b);
}
$c = mergeArray($a,$b);
var_dump($a);
var_dump($c);

您可以看到$c和$a是相同的。