PHP issues with functions (globals?)

Crashsector

[H]ard|Gawd
Joined
Jul 10, 2001
Messages
1,125
I'm back.

I have a function whose primary purpose is to set a few variables. These variables are to be used outside the function. I'm having problems making them do this.

I understand that variables in the script (outside the function) aren't available inside the function (this isn't a problem), but I can't seem to access the variables set inside the function from the rest of the script.

For example:

PHP:
function testfunction( $x ) {
$y = $x."a";
}
testfunction( '2' );
echo $y;

For whatever reason, nothing is returned. I would like the last line to return '2a'.

This is probably dirt easy, but you never know. Thanks!
 
Well, you could make $y a global or a session variable but you could also simply put a return statement in the testfunction like so...

return $y;

Then when you call the function it would look like this...

$result = testfunction(2);
echo $result;

Try that out and see if that works for you.
 
No go. This seems so simple, but then again, most things do at the beginning...

[edit]If it makes a difference, I have three variables that I need to be available outside the script, not just one.[/edit]
 
If you have more than one variable that you need to make available outside ofthe function then you might check into making them global variables or session variables. I'm not quite as versed in PHP yet as some of the others that frequent these forums so there may be a better way.
 
After actually opening my PHP book (ick), I realized globals are what I needed. The reason they didn't work last time is I was setting the variable, then defining it as global. You need to do this the other way around for it to work.

Whodathunkit.
 
Back
Top