1

Once I pass a variable inside a function as a reference, if I later access it, is it still a reference or..?

Example:

function one(){
    $variables = array('zee', 'bee', 'kee');
    $useLater =& $variables;
    two($variables);
}

function two($reference){
    foreach($reference as $variable){
        echo 'reference or variable, that is the question...';
    }
}

In function two(); are the variables here a reference to previously set $variables or a new element is created (in memory, I guess..)?

Plus, one more, is there a way to check if variable is passed by reference or not? (like: is_reference();)

tomsseisums
  • 13,168
  • 19
  • 83
  • 145

5 Answers5

2

As defined above the function two will use a new copy of $refernce.

To use the original variable you need to define function two like this:

function two(&$ref) {
  //> Do operation on $ref;
}
dynamic
  • 46,985
  • 55
  • 154
  • 231
1

variable. look:

function one(){
    $variables = array('zee', 'bee', 'kee');
    $useLater =& $variables;
    two($variables);
    var_dump($variables);
}

function two($reference){
    $reference = array();
}

gives

array(3) { [0]=> string(3) "zee" [1]=> string(3) "bee" [2]=> string(3) "kee" }

so changing it in two() diesn't change it in one(), so it's variable.

k102
  • 7,861
  • 7
  • 49
  • 69
1

A variable is only passed by reference (in current versions of PHP), if you explicitly pass it by reference using &$foo.

Equally, when declaring a variable to a new variable, such as $foo = $bar, $foo will be a reference to $bar until the value changes. Then it is a new copy.

There are lots of ways of detecting a reference here, maybe check some of them out. (Why you would need to do this is unknown, but still, it is there).

http://www.php.net/manual/en/language.references.spot.php

Layke
  • 51,422
  • 11
  • 85
  • 111
0

If you want the parameter for the function to be a reference, you have to write an & there, too.

Only exception should be objects.

Christoph Grimmer
  • 4,210
  • 4
  • 40
  • 64
0

Just try it out for yourself:

<?php

$variables = array('zee', 'bee', 'kee');
one($variables);

foreach($variables as $variable2){
        echo "original: ".$variable2."<br>";
    }


function one(&$variables){

    $useLater =& $variables;
    two($variables);

    foreach($variables as $variable2){
        echo "function one: ".$variable2."<br>";
    }

}

function two(&$reference){
    foreach($reference as $variable){
        echo "function two: ".$variable."<br>";
    }
    $reference[0] = 'lee';
}

?>

Now leave out the &-sign and see what happens. You will need to tell PHP explicitly everytime how you intend to pass on the variable in question.

Frank Vilea
  • 8,323
  • 20
  • 65
  • 86