When using complex/non-primitive/reference data types as method parameters in Java, a reference to the object is passed to the method:
public class Test {
public static void main(String[] args) {
String[] array = {"a", "b", "c", "d", "e"};
System.out.println(Arrays.toString(array)); // [a, b, c, d, e]
reverseArray(array);
System.out.println(Arrays.toString(array)); // [e, d, c, b, a]
}
private static void reverseArray(String[] array) {
int startIndex = 0;
int endIndex = array.length - 1;
String tmp;
while (endIndex > startIndex) {
tmp = array[endIndex];
array[endIndex] = array[startIndex];
array[startIndex] = tmp;
endIndex--;
startIndex++;
}
}
}
In contrast PHP seems to "copy" method parameters:
<?php
Test::main();
class Test {
public static function main() {
$array = ["a", "b", "c", "d", "e"];
print_r($array); // [a, b, c, d, e]
self::reverseArray($array);
print_r($array); // [a, b, c, d, e]
}
private static function reverseArray($array) {
$startIndex = 0;
$endIndex = count($array) - 1;
$tmp;
while ($endIndex > $startIndex) {
$tmp = $array[$endIndex];
$array[$endIndex] = $array[$startIndex];
$array[$startIndex] = $tmp;
$endIndex--;
$startIndex++;
}
}
}
Only when adding & to the method parameter, PHP will pass a reference to the object:
<?php
Test::main();
class Test {
public static function main() {
$array = ["a", "b", "c", "d", "e"];
print_r($array); // [a, b, c, d, e]
self::reverseArray($array);
print_r($array); // [e, d, c, b, a]
}
private static function reverseArray(&$array) {
$startIndex = 0;
$endIndex = count($array) - 1;
$tmp;
while ($endIndex > $startIndex) {
$tmp = $array[$endIndex];
$array[$endIndex] = $array[$startIndex];
$array[$startIndex] = $tmp;
$endIndex--;
$startIndex++;
}
}
}
If I want to simulate PHP's "default" behaviour (without the &) in Java, I have to copy the array:
public class Test {
public static void main(String[] args) {
String[] array = {"a", "b", "c", "d", "e"};
System.out.println(Arrays.toString(array)); // [a, b, c, d, e]
reverseArray(Arrays.copyOf(array, array.length));
System.out.println(Arrays.toString(array)); // [a, b, c, d, e]
}
private static void reverseArray(String[] array) {
int startIndex = 0;
int endIndex = array.length - 1;
String tmp;
while (endIndex > startIndex) {
tmp = array[endIndex];
array[endIndex] = array[startIndex];
array[startIndex] = tmp;
endIndex--;
startIndex++;
}
}
}
My questions are now:
- Does PHP copy every method parameter when I do not specifically use references? If yes, is this not very expensive (in regards of computation time and space)?
- Why are Java and PHP using different "default" methods of passing method parameters? Is there a clear advantage to one way or another?