开发者

Reference or variable?

Once I pass开发者_JS百科 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();)


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;
}


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


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.


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

Only exception should be objects.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜