Why isn't this example of call by reference not working? - php

I am clearing the concept of call-by-reference.Can anyone please explain the code lines below shown as an example of call-by-reference?
<?php
function test(){
$result = 10;
return $result;
}
function reference_test(&$result){
return $result;
}
reference_test($result);
?>

You have two problems.
$result is never set and the test function is never called.
You do a pass by reference on the wrong function. A pass by reference is to change the variable inside and outside the function.
Here is the solution, changed the function a bit to show you the difference. You don't need to return the variable you changed by reference.
// Pass by ref: because you want the value of $result to change in your normal code.
// $nochange is pass by value so it will only change inside the function.
function test(&$result, $nochange){
$result = 10;
$nochange = 10;
}
// Just returns result
function reference_test($result){
return $result;
}
$result = 0; // Set value to 0
$nochange = 0;
test($result, $nochange); // $result will be 10 because you pass it by reference in this function
// $nochange wont have changed because you pass it by value.
echo reference_test($result); // echo's 10
echo reference_test($nochange); // echo's 0

Related

no matter what I do my code would result the same

I wonder why I am getting the result as 4
<?php
function minusNum($aNum){
$result=$aNum-1;
return $result;
}
$theNum=4;
minusNum($theNum);
echo $theNum;
?>
Your minusNum function returns a new value, it doesn't manipulate the inputted $aNum. You should use that returned value. E.g.:
$result = minusNum($theNum);
echo $result;
You need to capture the result from your function.
<?php
function minusNum($aNum){
$result = $aNum - 1;
return $result;
}
$theNum = 4;
$theNum = minusNum($theNum);
echo $theNum;
?>
Here you assign the result of the function back to your original variable $theNum.
Although you pass the variable into the function, it is only altered inside the function. The value remains the same outside of the function.
<?php
function minusNum($aNum){
$result=$aNum-1;
return $result;
}
$theNum=4;
echo minusNum($theNum);
?>
Echo the function because it returns result
but when you echo $theNum you will get the $theNum value which is 4.
Moreover the function will grape the value of any value variable that passes through not the variable it self. so you contradicting youself. I hope it helps.

Calling a PHP function by reference behaving unexpectedly

Iwonder why the out put is 0(zero) for below code snippet? Can anyone please clarify why below code output is zero.
<?php
function a($number)
{
return (b($number) * $number);
}
function b(&$number)
{
++$number;
}
echo a(5); // output 0(zero) ?
?>
You never return any value from the function, and you're trying to echo the return value.
function b(&$number)
{
return ++$number;
}
Note that this is a silly example for a function that takes its parameter by reference, since you don't have a reference to the original value 5. Something like this would be more appropriate:
function b( &$number) {
++$number;
}
$num = 5;
b( $num);
echo $num; // Prints 6
The function name is b, but you are calling a...
Also, you are echoing a function, that doesn't return a value. This means you are echoing a non-initialize variable.
You must either return a value:
return ++$number;
or echo the variable directly:
$number = 5;
b($number);
echo $number;

Array not working (custom points system)

I am making a points system. I made an array that holds the points needed to level up, but it does not work.
Here is the code:
$level_stats = array();
$level_stats[1] = 50;
$level_stats[2] = 100;
$level_stats[3] = 175;
$level_stats[4] = 250;
$level_stats[5] = 350;
$level_stats[6] = 500;
$level_stats[7] = 700;
$level_stats[8] = 950;
$level_stats[9] = 1250;
$level_stats[10] = 2000;
function getLevelRequirementForUser($name){ // function to get needed points to level up
$level = tonumber(getLevelForUser($name)); // returns 1 (function not shown in code, it works though)
return $level_stats[$level]; // returns nothing.
}
First of all, your array is defined outside the scope of the function. When you try to access the $level_stats inside the function, it is accessing a local variable, which is undefined in your case. That is why it is not returning anything.
You can solve this by either using the global keyword, or passing the array as a parameter to the function.
1)
function getLevelRequirementForUser($level_stats, $name){ // function to get needed points to level up
$level = tonumber(getLevelForUser($name)); // returns 1 (function not shown in code, it works though)
return $level_stats[$level]; // returns nothing.
}
2)
function getLevelRequirementForUser($name){ // function to get needed points to level up
global $level_stats;
$level = tonumber(getLevelForUser($name)); // returns 1 (function not shown in code, it works though)
return $level_stats[$level]; // returns nothing.
}
This appears to be a simple scoping problem. The $level_stats array is not in the function's scope.
If you don't need $level_stats anywhere else, you could simply define it within your function, eg
function getLevelRequirementForUser($name) {
$level_stats = array(
1 => 50,
2 => 100,
// etc
);
$level = tonumber(getLevelForUser($name));
return $level_stats[$level];
}
You need to globalize your variable:
function getLevelRequirementForUser($name){
global $level_stats;
$level = tonumber(getLevelForUser($name));
return $level_stats[$level];
}

PHP newbie question: return variable with function?

i've been coding asp and was wondering if this is possible in php:
$data = getData($isEOF);
function getData($isEOF=false)
{
// fetching data
$isEOF = true;
return $data;
}
the function getData will return some data, but i'd like to know - is it possible to also set the $isEOF variable inside the function so that it can be accessed from outside the function?
thanks
It is possible, if your function expects it to be passed by reference :
function getData(& $isEOF=false) {
}
Note the & before the variable's name, in the parameters list of the function.
For more informations, here's the relevant section of the PHP manual : Making arguments be passed by reference
And, for a quick demonstration, consider the following portion of code :
$value = 'hello';
echo "Initial value : $value<br />";
test($value);
echo "New value : $value<br />";
function test(& $param) {
$param = 'plop';
}
Which will display the following result :
Initial value : hello
New value : plop
Using the global statement you can use variables in any scope.
$data = getData();
function getData()
{
global $isEOF;
// fetching data
$isEOF = true;
return $data;
}
See http://php.net/manual/en/language.variables.scope.php for more info.
Yes, you need to pass the variable by reference.
See the example here : http://www.phpbuilder.com/manual/functions.arguments.php

What does & before the function name signify?

What does the & before the function name signify?
Does that mean that the $result is returned by reference rather than by value?
If yes then is it correct? As I remember you cannot return a reference to a local variable as it vanishes once the function exits.
function &query($sql) {
// ...
$result = mysql_query($sql);
return $result;
}
Also where does such a syntax get used in practice ?
Does that mean that the $result is returned by reference rather than by value?
Yes.
Also where does such a syntax get used in practice ?
This is more prevalent in PHP 4 scripts where objects were passed around by value by default.
To answer the second part of your question, here a place there I had to use it: Magic getters!
class FooBar {
private $properties = array();
public function &__get($name) {
return $this->properties[$name];
}
public function __set($name, $value) {
$this->properties[$name] = $value;
}
}
If I hadn't used & there, this wouldn't be possible:
$foobar = new FooBar;
$foobar->subArray = array();
$foobar->subArray['FooBar'] = 'Hallo World!';
Instead PHP would thrown an error saying something like 'cannot indirectly modify overloaded property'.
Okay, this is probably only a hack to get round some maldesign in PHP, but it's still useful.
But honestly, I can't think right now of another example. But I bet there are some rare use cases...
Does that mean that the $result is returned by reference rather than by value?
No. The difference is that it can be returned by reference. For instance:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = a($c);
$d++;
echo $c; //echoes 1, not 2!
To return by reference you'd have to do:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = &a($c);
$d++;
echo $c; //echoes 2
Also where does such a syntax get used in practice ?
In practice, you use whenever you want the caller of your function to manipulate data that is owned by the callee without telling him. This is rarely used because it's a violation of encapsulation – you could set the returned reference to any value you want; the callee won't be able to validate it.
nikic gives a great example of when this is used in practice.
<?php
// You may have wondered how a PHP function defined as below behaves:
function &config_byref()
{
static $var = "hello";
return $var;
}
// the value we get is "hello"
$byref_initial = config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We still get "hello"
// However, let’s make a small change:
// We’ve added an ampersand to the function call as well. In this case, the function returns "world", which is the new value.
// the value we get is "hello"
$byref_initial = &config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We now get "world"
// If you define the function without the ampersand, like follows:
// function config_byref()
// {
// static $var = "hello";
// return $var;
// }
// Then both the test cases that we had previously would return "hello", regardless of whether you put ampersand in the function call or not.

Categories