工作中,使用参数传递这是很正常的一件事情,那么在php中对象引用传递还是值传递?
下面来看一个实例:
$x = new stdClass();
$x->prop = 1;
function f ( $o ) // Notice the absence of &
{
$o->prop ++;
}
f($x);
echo $x->prop; // shows: 2
?>
This is different for arrays:
<?php
$y = [ 'prop' => 1 ];
function g( $a )
{
$a['prop'] ++;
echo $a['prop']; // shows: 2
}
g($y);
echo $y['prop']; // shows: 1从上的例子中很容易就可以看出来,stdClass 这是一个对象,对象在php中的传递默认就是引用传递。
其他类型都是值传递,如果其他类型需要引用传递,在变量前边 添加 & 这个符号即可。
举例说明下
function sum(&$num){
return ++$num;
}
$n=10;
echo sum($n);