php中數組傳遞默認是按照值傳遞,對象傳遞是按照引用傳遞。
簡單舉個例子:
<?php
function testArray($arr){// &$arr
$arr = array(1,2,3,);
}
$array = array(4, 5);
testArray($array);
print_r($array);// Array ( [0] => 4 [1] => 5 )
如果testArray的參數寫成$arr,那麼數組$array的結果不會變。證明是按照值傳遞。
如果參數強制改成引用傳遞,函數參數要寫成&$arr,結果才是Array ( [0] => 1 [1] => 2 [2] => 3 )
再舉一個對象的例子:
<?php
class Person{
public $age = 0;
function __construct($age)
{
$this->age = $age;
}
}
function testObj($p){
$p->age = 2;
}
$p1 = new Person(1);
echo $p1->age,'<br/>';// 1
testObj($p1);
echo $p1->age;// 2
這個就證明了php對象傳遞是按照引用傳遞的。