[PHP] The reference of function

Assume that we have such function:

 

function testRef(&$a = array(10, 20, 30))
{
echo "Test of reference.\n";
}

 

 

When we use it as below:

 

代码
/*
*
*Example 1
*
*/
testRef(
array(10, 30, 40));
//The out is :
//Fatal error: Only variables can be passed by reference



/*
*
*Example 2
*
*/
$a = array(10, 30, 40);
testRef(
$a);
//The out is :
//Test of reference.

 

 

If we remove the "&" from the function,

 

function testRef($a = array(10, 20, 30))
{
echo "Test of reference.\n";
}

 

 

The same test code:

代码
/*
*
*Example 3
*
*/
testRef(
array(10, 30, 40));
//The out is :
//Test of reference.



/*
*
*Example 4
*
*/
$a = array(10, 30, 40);
testRef(
$a);
//The out is :
//Test of reference.

 

So we got the note that, when using reference in function, we have first set the value to a variable, then call the function with the variable.

posted @ 2010-05-15 12:28  DavidHHuan  阅读(296)  评论(0编辑  收藏  举报