Reference Variables and ++ Smybol

Hey guys,

I never use these but I wan’t to get comfortable with them, I find them very confusing.

Say I have:

function reference2(&$val)
{
	return ++$val; // Why does this add 2?
}

$c = 200;
$d = &$a;

echo reference2($d);

So it starts by saying,

  1. Pass $d to Reference,
  2. $d is a Reference is whatever $c is,
  3. So it passes $c, since they share the same memory location
  4. so the &$val is actually really $c that’s being affected
  5. Then the return actually changes $c to ++,
    – Why does ++ before it add 2?

Then if you do the same thing but with this…
How come it only adds 1??

function &reference(&$val)
{
	return ++$val;
}

$a = 200;
$b = &$a;

echo reference($b);

This are really confusing.

What’s more is if you do

return $val++; //it will give me an error.

Okay I think I am partially understanding.
Thats cool JohnJokes, I hope that thing is automated :stuck_out_tongue:

I don’t see the point in doing a Reference Function, when the first example below does the same thing and it’s easier to read.


# EXAMPLE 1
$something = 200;

/** This sets $something even without a return */
function Blah(&$var)
{
	$var = $var + 10;
}
Blah($something);
echo $something; // OUTPUT = 210

# EXAMPLE 2
/** This sets $something but a return 
  is required if its a Reference Function */
function &Yeah(&$var)
{
	return $var = $var + 50;
}

echo '<br />';
Yeah($something);
echo $something; // OUTPUT = 260

It doesn’t add 2, I suspect that you are calling ref($b) and ref($d), which both point to $a so $a will be incremented twice.

return $val++; won’t give you an error, the difference is that if $val = 200, with ++$val the function will return 201, but with $val++ the function will return $200 and then set $val to 201.

I was intrigued with your problem, played about with your code but was unable to replicate the errors?

http://johns-jokes.com/downloads/sp/jream/

.