0

How can I do, that a variable will be available everything in raw PHP app? I have variable $var in one file. In second file, which is included to first file, I have $var available, but if fhere is a class definition in second file, the variable is unavailable in that class. I need to do, the variable will be available everywhere, also inside class definition. Something similar like $_Session. His can I do that?

  • `$_SESSION`-type variables are called superglobals. While you can't create your own superglobals directly, you can mimic the behavior a bit. 1. Defining the variable in the global namespace and use the [global](http://php.net/manual/en/language.variables.scope.php) keyword in other scopes. 2. Set up a static class with a public variable, [like this answer](https://stackoverflow.com/a/834804/2453432). – M. Eriksson Sep 19 '18 at 05:11
  • 1
    I would actually like to ask the question "Why are you trying to achieve this?" There could be a much better way to achieve what you want, without polluting the global scope as this could lead to unintended consequences later on. So please elaborate a bit more on why you need to achieve this – TommyBs Sep 19 '18 at 05:26
  • I need to get mysqli connection sverywhere. I am remaking an ancient php app, which still uses mysql_pconnect. There is a pconnect and everywhere, where I write mysql_query, the app knows, that it should use this connection. In mysqli_query I need to link a mysqli connection, so I need a variable with mysqli connection and link it everywhere, also inside classes as well –  Sep 19 '18 at 06:15

3 Answers3

0

const of class and namespace?

const of class in different namespace can get different value even the name of the variables are same

heihei
  • 74
  • 6
0

You can use $GLOBALS to achieve this.

According to PHP manual,

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

And the best thing, it is available in PHP 7 as well.

Amit Merchant
  • 1,045
  • 6
  • 21
0

Apart from $GLOABALS; You can also define constant by making use of define. (refer) These constants are also accessible everywhere.

for e.g.

define('my_var', 'value_here');

to access this variable you can use;

echo my_var;