PHP functions

C++, C#, Java, PHP, ect...
Post Reply
alexrules01
Posts: 175
Joined: Sun Oct 11, 2009 9:33 am

PHP functions

Post 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?
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: PHP functions

Post 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 
The indelible lord of tl;dr
User avatar
Callan S.
Posts: 2042
Joined: Sun Jan 24, 2010 5:43 am

Re: PHP functions

Post 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.
Fight Cycle : My latest Browser game WIP
Driftwurld : My Browser Game WIP
Philosopher Gamer : My Blog
alexrules01
Posts: 175
Joined: Sun Oct 11, 2009 9:33 am

Re: PHP functions

Post 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 :)
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: PHP functions

Post 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.
The indelible lord of tl;dr
Post Reply

Return to “Coding”