Topic: Call by Value/Referance

First of all I would Like to thank Killer Team for providing such a nice tutorial for OOP PHP.
I just read the tutorial and find it is very helpful for beginners.

I want to know about the Call By Value and Call By Referance in the same simple way.

Thank You

Vote up Vote down

Re: Call by Value/Referance

I don't have time at the moment to post fully at the moment, but I can dig up a code snippet that shows the difference later today.

Benjamin Falk | Falken Creative : Twitter
Skills: Photoshop, Illustrator, HTML, CSS, jQuery, PHP and CodeIgniter

Vote up Vote down

Re: Call by Value/Referance

Here's the code snippet that I was talking about. I just learned about this in my C++ class, actually, and was surprised to see that PHP does this as well. I haven't run into this before in a PHP based application.

Basically, the difference is that "Pass by Value" passes the value of the variable, while "Pass by Reference" passes the reference to the variable -- the variable itself. This will allow the function to modify variable passed to it. In this example, I start by setting a variable, $var, to 1. When I pass that variable to the by_value() function, you'll notice that the value of $var doesn't change. But, when I pass it to by_reference(), $var itself changes from 1 to 2.

(I'm only just getting into this concept, so if there is a better explanation or I've said something that isn't completely true, feel free to comment)

<?php
 
$var = 1;
 
 
 
// This is an example of "Pass by Value"
function by_value($i)
{
    $i++;
}
 
// When we pass $var into the function, it just passes $var's value, 1, not var itself.
// Any changes made within the function won't affect $var, so $var's value doesn't change.
// This will echo "1".
by_value($var);
echo "Pass by Value: " . $var . "<br/>";
 
 
 
// This is an example of "Pass by Reference" (notice the "&" before the variable name)
function by_reference(&$i)
{
    $i++;
}
 
// When you pass $var into the function, it isn't passing the value, but $var itself
// You can think of it like this: rather than $i just holding the value of $var, $i becomes $var,
// so any changes made to $i also affect $var.
// this will echo "2"
by_reference($var);
echo "pass by Reference: " . $var;
 
?>

More info:
http://php.net/manual/en/language.references.pass.php

Benjamin Falk | Falken Creative : Twitter
Skills: Photoshop, Illustrator, HTML, CSS, jQuery, PHP and CodeIgniter

Vote up Vote down

Re: Call by Value/Referance

Thank You "falkencreative"

Thanks for your nice example.

I want to ask more.

what is difference between 
                                         function fname() and function &fname()
and between return
                                         return $i; and return &$i;

Vote up Vote down