It's been a long time I've been thinking on how to deal with this kind of situation:
Take for instance the hash example:
hash = {'a' => 'b', 'c' => 'd'}
other = {'a' => 'd'}
hash.merge(other) # returns a new hash
hash.merge!(other) # modifies hash
How would you deal with that in php?
$hash = new Hash(array( 'a' => 'b', 'c' => 'd' ));
$other = new Hash(array('a' => 'd'));
Option params:
public function merge($other, array $options = array('mutate' => false))
{
}
// or
public function merge($other, $mutate = false)
{
}
Or perhaps two different method names:
public function merge($other)
{
}
public function mergeIntoSelf($other)
{
}
I kind of like the 'options param' approach, but what if the method actually receives another optional param, like in ruby, which is a modifier callback.
$hash->merge($other, function ($key, $originalValue, $otherValue) {
if ($key === 'foo') {
return $originalValue;
}
return $otherValue;
}, array('mutate' => true));
The callback option could be the third one, instead of the second one, but I don't like that. I also don't like the idea of checking the params and trying to find out what is what. They doc block gets hairy.
So I would like to hear your opinions on how you would approach that.
Thank you in advance.
You can use &
sign at function name but its not a good solition. i want to just give an idea its possible:
$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);
You can see that $c and $a will be same.