I mean a variable that will behave like PHP super global ($_POST,$_GET etc), so that once it is defined it becomes available to all scripts.
Asked
Active
Viewed 858 times
0
-
it can behave like PHP ordinal global variable as well. – Your Common Sense Apr 21 '13 at 20:53
-
2It is possible, but the question is whether you really want to do that... – kapa Apr 21 '13 at 20:54
-
3possible, yes; bad practice, yes. – Apr 21 '13 at 20:54
2 Answers
0
It is possible if you add an index to $GLOBALS
.
Like this:
$GLOBALS['foo'] = 'bar';
$GLOBALS
will be available in any scope.
Also you can just define a variable in the global scope. But to be available in functions it has to be declared in the function using the global
keyword.
$foo = 1;
function test() {
global $foo;
echo $foo;
}

hek2mgl
- 152,036
- 28
- 249
- 266
-
1
-
-
*General* in [software design](http://stackoverflow.com/a/1557799/164998). PHP being a dynamic language makes doing so easy. But that doesn't means its [good](http://stackoverflow.com/a/12446305/164998). – Jason McCreary Apr 22 '13 at 00:44
-
What makes your constant approach better? Btw, This post about software design that you've linked isn't a good one. If you cannot explain it with own words, then I have to assume that it is just *because other's say*. Btw, I can give you some reasons for being this a bad design. But this would just being reasons for particular situations and not in general. Sometimes it is just quite useful. As you see with `$_GET`, `$_POST`, ... – hek2mgl Apr 22 '13 at 00:47
-
Why do you need more when the community has spoken? Look around you. The only *upvotes* on this question are comments saying that globals are *generally bad practice* and be careful how you use them. The question itself is downvoted. That should tell you something. – Jason McCreary Apr 22 '13 at 00:57
-
Note that community is not always right. Last friday I've earned 4 upvotes for a wrong regex. (corrected this of course) – hek2mgl Apr 22 '13 at 00:58
-
0
You can do this by defining variables.
define(MY_VAR,"MY_VALUE");
You can go on and on and put all of them in a php file which you include in the other php files where you need those variables. You can select those variables like this:
include('VARS_FILE.php');
$var = MY_VAR;

Xandervr
- 74
- 5
-
Constants are not the same as vars. They are read only. What if you need to change the value? – hek2mgl Apr 21 '13 at 21:09
-
That's true, but it is a good way to use some constant vars, but why wouldn't you work with sessions? – Xandervr Apr 21 '13 at 21:14
-
I don't think that `$_SESSION` is the right approach to the question. What if it is a cli script? – hek2mgl Apr 21 '13 at 21:16