函数参数传递引用是很常见的问题,但是最近在使用PHP写网页的时候发现了这样的问题!
1
public function delete(&$arr){
2
unset($arr);
3
}
4
public function indexAction()
5
{
6
$arr = array(1,2,3,4,5);
7
$this->delete($arr);
8
print_r($arr);
9
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
7
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
8
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
9
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
代码很简单,在函数indexAction函数中定义数组,引用传递给delete函数;
在delete函数中将整个数组释放掉,
函数返回后在indeAction中打印$arr内容如下:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
但是删除数组中的第三个元素没有问题:
1
public function delete(&$arr){
2
unset($arr[2]);
3
}
4
public function indexAction()
5
{
6
$arr = array(1,2,3,4,5);
7
$this->delete($arr);
8
print_r($arr);
9
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
7
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
8
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
9
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
输出结果:
Array ( [0] => 1 [1] => 2 [3] => 4 [4] => 5 )
不知道是为什么;简单的解决办法:
将修改后的数组返回,希望如果谁有更好的办法告诉我!
1
public function delete(&$arr){
2
unset($arr);
3
return $arr;
4
}
5
public function indexAction()
6
{
7
$arr = array(1,2,3,4,5);
8
$arr = $this->delete($arr);
9
print_r($arr);
10
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
7
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
8
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
9
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
10
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)