Page 1 of 1

PHP functions

Posted: Sat Nov 12, 2011 10:02 am
by alexrules01
I must be mis-understanding PHP functions, as I make the most basic function, but it still doesn't work, somewhat.

I thought when you use the code return $value; that variable is returned to the main lines of code. But I try this:

Code: Select all

$value = 0;
function writeName($name,$value)
 {
 echo "My Name Is " . $name . "";
 $value = 3;
 return $value;
 }
 $name = "Alex";
 writeName($name,$value);
 print $value;
now I thought it would return $value at 3, but it doesnt. Can anyone clear it up?

Re: PHP functions

Posted: Sat Nov 12, 2011 10:13 am
by Jackolantern
Yes, you are misunderstanding how return values work ;)

When you call a function, you must assign the value returned into a variable. Just running the function won't change the value you passed in, because the function is working with that variable in another scope. Inside that function, where you are working with the variable $value, that isn't the same $value you were working with outside of the function. A copy was created and sent inside the function! Here is how you should write that code:

Code: Select all

$value = 0;

function writeName($name,$value)
{
    echo "My Name Is " . $name . "";
    $value = 3;
    return $value;
}

$name = "Alex";
$returned = writeName($name,$value);    //you must assign a variable here to get the result
print $returned;    //and then get show the results from that variable here 

Re: PHP functions

Posted: Sat Nov 12, 2011 11:09 am
by Callan S.
I think if you put a & symbol in front of $value

Code: Select all

function writeName($name,&$value)
It uses the same value as the rest of the program.

Re: PHP functions

Posted: Sat Nov 12, 2011 11:40 am
by alexrules01
Ahh once again, thanks Jack! I tried something similar to that, but still got an error. Now I can cut out a few lines of code! :P

I will try that out Callan, thanks for the info :)

Re: PHP functions

Posted: Sat Nov 12, 2011 6:54 pm
by Jackolantern
Yes, that is right Callen, as that makes it pass by reference. However, it is considered bad practice to use that in PHP because it is confusing to others who read your code and it flies in the face of the way PHP should work.