variable not in function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
calebsg
Forum Commoner
Posts: 28
Joined: Tue Jun 18, 2002 10:41 am

variable not in function

Post 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.
User avatar
martin
Forum Commoner
Posts: 33
Joined: Fri Jun 28, 2002 12:59 pm
Location: Cambridgeshire

Post 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
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
Post Reply