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.
Related
This question already has answers here:
Are PHP Variables passed by value or by reference?
(16 answers)
How to declare a global variable in php?
(10 answers)
Closed 3 years ago.
I would like to be able to assign the name of a variable outside the function so that the function can assign the chosen variable. It does not seem to work. Anyone have any ideas?
Below is my attempt, however the $admin variable is empty after running the function.
function assign_check($variable, $check) {
if (empty($_POST[$check])) {
$variable = "no";
} else {
$variable = $_POST[$check];
}
}
assign_check('$admin', 'admin');
My question is not about the use of global variables.
You can request a reference in the function body.
function assign_check(&$variable, $check) {
$variable = 'hello';
}
And call passing a variable (reference).
assign_check($admin, 'admin');
$admin value is now 'hello';
Fitting that to your code would result in
function assign_check(&$variable, $check) {
$variable = empty($_POST[$check]) ? "no" : $_POST[$check];
}
assign_check($admin', 'admin');
But returning a proper value would be much cleaner code than using references. Using a ternary operator like presented above would it even simplify without need of a function at all.
A normal way to assign the result of a function to a variable name specified outside the function would be to have the function return the result and assign it directly to the variable when you call the function.
function assign_check($check) {
if (empty($_POST[$check])) {
return "no";
} else {
return $_POST[$check];
}
}
$admin = assign_check('admin');
I would do it this way unless there was a compelling reason to do it otherwise.
For the specific type of thing it looks like this function is intended to do, I would suggest looking at filter_input.
This question already has answers here:
Using Default Arguments in a Function
(16 answers)
Closed 5 years ago.
when and where I should keep the Parameters Null or FALSE?
for stance here is a function... and what this function will do when i called it or how can i call it?
<?php
function Show_result($id=Null, $name=FALSE){
//whatever i want code goes here
}
?>
In this declaration you set default values so you can call this function without passing parameters.
This could be useful if you don't want to pass the same parameters most of the times but still be able to pass specific ones in other cases.
For example, a function like this :
function log($message, $tag = null) {
if ($tag == null)
$tag = "info";
echo $tag . ": " . $message;
}
This function can be called two ways:
log("text")
or
log("text", "error")
The first call will print
info: text
The second will print
error: text
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.
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
I'm 'dissecting' PunBB, and one of its functions checks the structure of BBCode tags and fix simple mistakes where possible:
function preparse_tags($text, &$errors, $is_signature = false)
What does the & in front of the $error variable mean?
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!
It does pass by reference rather than pass by value.
This allows for the function to change variables outside of its own scope, in the scope of the calling function.
For instance:
function addOne( &$val ) {
$val++;
}
$a = 1;
addOne($a);
echo $a; // Will echo '2'.
In the case of the preparse_tags function, it allows the function to return the parsed tags, but allow the calling parent to get any errors without having to check the format/type of the returned value.
It accepts a reference to a variable as the parameter.
This means that any changes that the function makes to the parameter (eg, $errors = "Error!") will affect the variable passed by the calling function.
It means that the variable passed in the errors position will be modified by the called function. See this for a detailed look.