Welcome to WebmasterWorld Guest from 54.161.228.30

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

PHP global variable

How to define a variable that keep the value alive in other file

   
10:02 am on Jul 24, 2008 (gmt 0)

5+ Year Member



Hi All,

I'm very new in this php world and I'd really appreciate your help.

I have 2 files. a.php and b.php

a.php contains a variable ($x) value that I want to use in b.php

b.php executes a.php: require_once('a.php') but this is not enough to pass the $x value.

How can I set $x global in order to user its value trough the other file?

Sorry about the naive nature of this question.
Thanks in advance.

2:32 pm on Jul 24, 2008 (gmt 0)

5+ Year Member



All you have to do is define the variable outside of a function; that makes it global. However, in order to use it INSIDE of a function, you need to declare it.

$g_szMyGlobalString = "Hello, World!"

function SomeFunction()
{
global $g_szMyGlobalString;

echo $g_szMyGlobalString;
}

3:23 pm on Jul 24, 2008 (gmt 0)

5+ Year Member



if you have $x in "a.php" (but not inside a function), you should have no trouble using it when you "include" it in "b.php". in the case that you do have it inside a function, you must declare it global like in the example above before you can "see" it in "b.php."
if you still have problems, feel free to post "a.php" and "b.php"