Functions and reference variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
prashanth.raju
Forum Newbie
Posts: 3
Joined: Mon Jul 05, 2010 5:58 am

Functions and reference variables

Post 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 />";
    ?>
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Functions and reference variables

Post 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?
prashanth.raju
Forum Newbie
Posts: 3
Joined: Mon Jul 05, 2010 5:58 am

Re: Functions and reference variables

Post 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...
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Functions and reference variables

Post by VladSun »

There are 10 types of people in this world, those who understand binary and those who don't
prashanth.raju
Forum Newbie
Posts: 3
Joined: Mon Jul 05, 2010 5:58 am

Re: Functions and reference variables

Post 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 />";
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Functions and reference variables

Post by Benjamin »

:arrow: Moved to PHP - Code
Post Reply