Page 1 of 1

variable not in function

Posted: Thu Jul 04, 2002 2:38 pm
by calebsg
Hi folks,

Go easy on me here 'cause I think there is an easy answer to this but I can't figure it out. :?

I have a variable at the top of my page and a case statement then some functions down below. However, the variable at the top doesn't get passed down into the functions. I have to restate it in the function.

Pseudo-code:

Code: Select all

$pie = "apple";

switch "submit" {
case "submit pie":
  MyPie($submit);
  break;
default:
  break;
}

function MyPie($submit) {
 echo $pie;
}
that echo won't output anything unless I change the function to:

Code: Select all

function MyPie($submit) {
 $pie = "apple";
 ecoh $pie;
}
I haven't bothered to make sure I have every apostraphe, semicolon and comma in here, I just need to know why the variable needs redeclared or whatever you call it.

Thanks a bunch in advance.

Posted: Thu Jul 04, 2002 2:53 pm
by martin
It all comes down to variable scope and bless the guys at php.net for this tutorial:
http://www.php.net/manual/en/language.v ... .scope.php

Posted: Fri Jul 05, 2002 1:48 am
by twigletmac
Yep, functions in PHP can be tricky things.

Code: Select all

function MyPie($submit) { 
    global $pie;
    echo $pie; 
}
Basically they don't know that specific variables exist unless you declare them global, pass them as an argument or access them from one of the autoglobal arrays ($_SESSION, $_POST, $_GET etc).

Mac