olli olli - 1 year ago 109
PHP Question

make variable available to all classes, methods, functions and includes, just like $_POST

This question seems simple enough, but I can't find an answer anywhere...

At the beginning of my php script/file I want to create a variable.

$variable = 'this is my variable';

I want this variable to be available within the entire script, so that all classes, methods, functions, included scripts, etc. can simple call this variable as $variable.

Class MyClass
public function showvariable()
echo $variable;

The $_SESSION, $_POST, $_GET variables all behave like that. I can just write a method and use $_POST and it'll work. but if I use $variable, which I have defined at the beginning of my script, it says "Notice: Undefined variable: variable in ..." It even says it, when I write a function, rather than a class method...

I tried to write

global $variable = 'this is my variable';

But then the script wouldn't load...
"HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request."

How can I make a variable truly globally accessible like $_POST?

Why would I need this? I specifically plan on using it as a form token. At the top of the page I generate my form token as $token, at the bottom of the page I store it in the session. Before handling any form I check if the SESSION token matches the POST token... And since I often have multiple forms on the page (login form in the top nav, and register form in the main body) i just wanna make it convenient and call $token on each form. Sometimes my formelements are generated by classes or functions, but they don't recognize the variable and say it's not defined.

Answer Source

I found it... -.- I thought it would be easy enough...

I have to call to the variable by using


Just found it... finally... http://php.net/manual/en/reserved.variables.globals.php

EDIT like 8 months later or so:

I just learned about CONSTANTS!

define('name', 'value');

They just can't be reassigned... I guess I could use that, too! http://www.php.net/manual/en/language.constants.php

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download