views:

91

answers:

3

What is Call Time Pass Reference? What does it do?

+1  A: 

I assume you mean Call Time Pass By Reference.

In PHP, the & operator will get the reference of the variable (There is lots of info on this on stackoverflow)

Call time pass by reference is where you pass a reference as an argument to a function that doesn't take a reference

function foo($myParam){
}

//Call Time Pass By Reference
foo(&$myArg);

This will give a warning in PHP 5.3 as it as been deprecated and it will be passed by value. The correct way to do it is to alter the function foo to take a reference

function foo(&$myParam){
}

foo($myArg); //myArg is passed by reference

The ability to preform call time pass by reference is controlled by the ini setting

allow_call_time_pass_reference

In more recent releases this is off by default.

The reason why it is bad is that the function (and reader) doesn't know which parameters are references and which aren't. It makes the code a lot harder to follow.

Yacoby
+1  A: 

The PHP manual explains it:

Nowadays, references are declared with the function declaration like this:

function foo (&$bar) {
  // changing $bar changes the original variable
}

However, the syntax also allows for passing a variable by reference, when you call the function:

foo(&$bar);

and that is deprecated, since it is considered bad style and error-prone. (If a function doesn't know, if it acts on a copy or the original variable, you can think of any mischief happening.)

The latter one is called call time pass by reference, since the reference is passed at function call time. (Hm... The first rule of the tautology club is the first rule of the tautology club.)

Boldewyn
+1  A: 

In PHP when you pass the value to a function it is copied for function to use it so outside of the function the value is intact. This is called passing by value. If you want to modify value inside the function you would make a pass by reference (pass a pointer to a value, not the value itself). I PHP this is done by using & character.

$a = 1;

function b($a) {
    $a + 1;
    echo $a;
}

echo $a; // print 1
echo b($a); // print 2
echo $a; // $a is still 1
echo b(& $a); // print 2
echo $a; // $a is now 2

If you want to pass a reference you have two ways of doing that in PHP and one of it (call-time) is deprecated.

Call-time pass by reference:

b(& $a);

What you should do instead is change your function declaration and add & there.

// declare reference parameter
function b(& $a) {
    ...
}

b($a); // pass by reference
RaYell