Page 1 of 1

Functions and reference variables

Posted: Mon Jul 05, 2010 6:09 am
by prashanth.raju
From the below code can anyone explain me why the value of the variable "$value" is returned as 56 in both echo's and not as 101 and 1001??

Code: Select all

<?php
    $a="php";
    $php="PHP Programming is cool...<br />";
    echo $$a;
    
    function &increment($i){
        $i++;
        return $i;
    }
    
    $value=&increment(55);
    increment(100);
    echo "$value<br />";
    increment(1000);
    echo "$value<br />";
    ?>

Re: Functions and reference variables

Posted: Mon Jul 05, 2010 6:13 am
by Apollo
That's because of this line:
prashanth.raju wrote:$value=&increment(55);

This assignes 56 to $value.

Why do you think that the other two function calls (increment(100) and increment(1000)) would have any influence on $value?

Re: Functions and reference variables

Posted: Mon Jul 05, 2010 6:31 am
by prashanth.raju
variable "$value" and function "increment($i)" are referencing each other...
so when the function is called (i.e., i mean increment(100), increment(1000)), the new values passed to the function should get incremented and not the older value which was passed in this line:

Code: Select all

$value=&increment(55);
why is that calling the function "increment(100)" and "increment(1000)" not having any effect in the code??

please correct me if am wrong...

Re: Functions and reference variables

Posted: Mon Jul 05, 2010 6:50 am
by VladSun

Re: Functions and reference variables

Posted: Mon Jul 05, 2010 7:54 am
by prashanth.raju
i got the answer to my question... thanks...

I modified my code like this and now it gives the expected result of 101 and 1001

Code: Select all

function &increment(&$i){
        $i++;
        return $i;
    }
    $j=55;
    $value=&increment($j);
    $j=100;
    increment($j);
    echo "$value<br />";
    $j=1000;
    increment($j);
    echo "$value<br />";

Re: Functions and reference variables

Posted: Mon Jul 05, 2010 8:58 am
by Benjamin
:arrow: Moved to PHP - Code