This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
what is the meaning of &$variable
and meaning of functions like
function &SelectLimit( $sql, $nrows=-1, $offset=-1, $inputarr=false, $secs2cache=0 )
{
$rs =& $this->do_query( $sql, $offset, $nrows, $inputarr);
return $rs;
}
Passing an argument like so: myFunc(&$var); means that the variable is passed by reference (and not by value). So any modifications made to the variable in the function modify the variable where the call is made.
Putting & before the function name means "return by reference". This is a bit very counter-intuitive. I would avoid using it if possible. What does it mean to start a PHP function with an ampersand?
Be careful not to confuse it with the &= or & operator, which is completely different.
Quick test for passing by reference:
<?php
class myClass {
public $var;
}
function incrementVar($a) {
$a++;
}
function incrementVarRef(&$a) { // not deprecated
$a++;
}
function incrementObj($obj) {
$obj->var++;
}
$c = new myClass();
$c->var = 1;
$a = 1; incrementVar($a); echo "test1 $a\n";
$a = 1; incrementVar(&$a); echo "test2 $a\n"; // deprecated
$a = 1; incrementVarRef($a); echo "test3 $a\n";
incrementObj($c); echo "test4 $c->var\n";// notice that objects are
// always passed by reference
Output:
Deprecated: Call-time pass-by-reference has been deprecated; If you would like
to pass it by reference, modify the declaration of incrementVar(). [...]
test1 1
test2 2
test3 2
test4 2
The ampersand - "&" - is used to designate the address of a variable, instead of it's value. We call this "pass by reference".
So, "&$variable" is the reference to the variable, not it's value. And "function &func(..." tells the function to return the reference of the return variable, instead of a copy of the variable.
See also:
difference between function and &function
http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference
http://www.php.net/manual/en/language.references.pass.php
http://www.adp-gmbh.ch/php/pass_by_reference.html
Related
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 2 years ago.
condition in array_map is true, has inserted data and print statement inside condition. But why it doesn't return variable value. Here sucesss is printing, but $var variable's value is not updating. Array map returns array only, does it relate here ?
$var = 'fail';
array_map(function ($en, $np, $idSrvcs) {
$data=[Fnct::filter_int($idSrvcs),Fnct::filter_str($en),Fnct::filter_str($np)];
if(MdlDb::insrtData('srvcs_dtl',$data,'')){
echo 'success'; // this line is printing
$var = 'success';
}
}, $en, $np, $idSrvcs);
echo $var // here output is fail.
Because the variable $var in the anonymous function (the callback for array_map) has its own scope and it is a different variable. You can check by dumping $var before assigning value to it. It will be undefined, not 'fail'.
You can pass variables from parent scope inside the function with use keyword, like this:
// Inherit $message
$example = function () use ($message) {
var_dump($message);
};
$example();
From https://www.php.net/manual/en/functions.anonymous.php Example #3 Inheriting variables from the parent scope.
Take note that just passing the variable wont be enough to modify it because function retrieves the copy (object would be passed by reference):
$s = 1;
$a = function () {$s++;};
$a(); // PHP Notice: Undefined variable: b
var_dump($s); // 1
$b = function () use ($s) {$s++;};
$b();
var_dump($s); // 1
$c = function () use (&$s) {$s++;};
$c();
var_dump($s); // 2
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 8 years ago.
What does "&" mean in '&$var' in PHP? Can someone help me to explain this further. Thank you in advance.
It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.
function passByReference(&$test) {
$test = "Changed!";
}
function passByValue($test) {
$test = "a change here will not affect the original variable";
}
$test = 'Unchanged';
echo $test . PHP_EOL;
passByValue($test);
echo $test . PHP_EOL;
passByReference($test);
echo $test . PHP_EOL;
Output:
Unchanged
Unchanged
Changed!
You can pass a variable to a function by reference. This function will be able to modify the original variable.
You can define the passage by reference in the function definition with &
for example..
<?php
function changeValue(&$var)
{
$var++;
}
$result=5;
changeValue($result);
echo $result; // $result is 6 here
?>
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend
an ampersand (&) to the argument name in the function definition.
This question already has answers here:
PHP param by ref => assign to ref = NULL
(1 answer)
PHP's assignment by reference is not working as expected
(7 answers)
Closed 8 years ago.
Here is the simplified version of code that might be revealing a PHP bug
class AClass
{
public static $prop = "Hi";
}
function assignRef (&$ref)
{
$ref = &AClass::$prop;
echo "inside assignRef: $ref\n";
}
$ref = "Hello";
assignRef($ref);
echo "outside: $ref\n";
This prints out
inside assignRef: Hi
outside: Hello
Shouldn't $ref had been assigned by reference to $prop static variable of the AClass class and become "Hi" not just inside assignRef function but also outside of it?
The class in your example is irrelevant, simplified version that produces the same output:
function assignRef (&$ref)
{
$prop = 'Hi';
$ref = &$prop;
echo "inside assignRef: $ref\n";
}
$ref = "Hello";
assignRef($ref);
echo "outside: $ref\n";
What is happening is that when assigning by reference inside the function ($ref = &$prop;) you are just changing what one variable is pointing to, not changing the value of what it was originally pointing to nor changing any other references to that original value.
You effectively have two variables called $ref in this example - one inside the function, and one outside the function. You are changing what the variable inside the function points to, leaving the other variable pointing to the original (unchanged) value.
Consider the following code:
$a = 'a';
$b = 'b';
$c = 'c';
$a = &$b;
$b = &$c;
echo "$a / $b / $c";
This results in output of b / c / c, rather than what you might expect c / c / c. This happens for the same reason - assignment by reference does not affect the value originally referenced nor change any other references, meaning any other variables pointing to the original value are unchanged.
If you want to change the value, rather than creating a new reference to another value, you must use normal assignment (=). Alternatively, you could change all references.
(1) I want to know what is the difference between call by value and call by reference in php. PHP works on call by value or call by reference?
(2) And also i want to know that do you mean by $$ sign in php
For example:-
$a = 'name';
$$a = "Paul";
echo $name;
output is Paul
As above example what do u mean by $$ on PHP.
$$a = b; in PHP means "take the value of $a, and set the variable whose name is that value to equal b".
In other words:
$foo = "bar";
$$foo = "baz";
echo $bar; // outputs 'baz'
But yeah, take a look at the PHP symbol reference.
As for call by value/reference - the primary difference between the two is whether or not you're able to modify the original items that were used to call the function. See:
function increment_value($y) {
$y++;
echo $y;
}
function increment_reference(&$y) {
$y++;
echo $y;
}
$x = 1;
increment_value($x); // prints '2'
echo $x; // prints '1'
increment_reference($x); // prints '2'
echo $x; // prints '2'
Notice how the value of $x isn't changed by increment_value(), but is changed by increment_reference().
As demonstrated here, whether call-by-value or call-by-reference is used depends on the definition of the function being called; the default when declaring your own functions is call-by-value (but you can specify call-by-reference via the & sigil).
Let's define a function:
function f($a) {
$a++;
echo "inside function: " . $a;
}
Now let's try calling it by value(normally we do this):
$x = 1;
f($x);
echo "outside function: " . $x;
//inside function: 2
//outside function: 1
Now let's re-define the function to pass variable by reference:
function f(&$a) {
$a++;
echo "inside function: " . $a;
}
and calling it again.
$x = 1;
f($x);
echo "outside function: " . $x;
//inside function: 2
//outside function: 2
You can pass a variable by reference to a function so the function can modify the variable.
More info here.
Call by value: Passing the variable value directly and it will not affect any global variable.
Call by reference: Passing the address of a variable and it will affect the variable.
It means $($a), so its the same as $name (Since $a = 'name'). More explanation here What does $$ (dollar dollar or double dollar) mean in PHP?
Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.
Call by reference means passing the address of a variable where the actual value is stored. The called function uses the value stored in the passed address; any changes to it do affect the source variable.
Please see this code:
function addCounter(&$userInfoArray) {
$userInfoArray['counter']++;
return $userInfoArray['counter'];
}
$userInfoArray = array('id' => 'foo', 'name' => 'fooName', 'counter' => 10);
$nowCounter = addCounter($userInfoArray);
echo($userInfoArray['counter']);
This will show 11.
But! If you remove "&"operator in the function parameter, the result will be 10.
What's going on?
The & operator tells PHP not to copy the array when passing it to the function. Instead, a reference to the array is passed into the function, thus the function modifies the original array instead of a copy.
Just look at this minimal example:
<?php
function foo($a) { $a++; }
function bar(&$a) { $a++; }
$x = 1;
foo($x);
echo "$x\n";
bar($x);
echo "$x\n";
?>
Here, the output is:
1
2
– the call to foo didn’t modify $x. The call to bar, on the other hand, did.
Here the & character means that the variable is passed by reference, instead of by value. The difference between the two is that if you pass by reference, any changes made to the variable are made to the original also.
function do_a_thing_v ($a) {
$a = $a + 1;
}
$x = 5;
do_a_thing_v($x);
echo $x; // echoes 5
function do_a_thing_r (&$a) {
$a = $a + 1;
}
$x = 5;
do_a_thing_v($x);
echo $x; // echoes 6
When using the ampersand prior to a variable in a function call, it associates with the original variable itself. With that, the code you posted is saying that it will add 1 to the counter of the original array. Without the ampersand, it takes a copy of the data and adds to it, then returns the new counter of 11. The old array still remains intact at 10 and the new counter variable returned turns into 11.
http://www.phpreferencebook.com/samples/php-pass-by-reference/
is a good example.
Maybe I can add to the other answers that, if it is an object, then it is not "the object passed as value", but it is "the object's reference is passed as a value" (although I am asking what the difference is between "the object is passed by reference" vs "the object's reference is passed by value" in the comments). An array is passed by value by default.
Information: Objects and references
Example:
class Foo {
public $a = 10;
}
function add($obj) {
$obj->a++;
}
$foo = new Foo();
echo $foo->a, "\n";
add($foo);
echo $foo->a, "\n";
Result:
$ php try.php
10
11