arxoft
arxoft

Reputation: 1475

Is it possible to declare a variable as "always global"?

Is there any way I can define a variable such a way that I don't need to global $var1; in every function? Just define it in beginning and keep using where ever needed. I know $GLOBALS exist, but don't want to use it.

Upvotes: 1

Views: 207

Answers (3)

sectus
sectus

Reputation: 15454

This behaviour called as superglobal variable. But php has limited predefined list of them: Superglobals.

So you cannot add your own superglobal variable.

Variable scope

My suggestions from the most to less radical:

  • Edit source code of PHP and add your own superglobals.
  • Do not write code at all.
  • Do not use PHP (use different language with different variable scope policy).
  • Do not use functions (write plain script).
  • Use constants instead of variables.
  • Use function params instead of using globals.
  • Use static variables instead of globals. (\G::$variable)

Upvotes: 0

Ryan
Ryan

Reputation: 14649

First let me try to explain why you shouldn't use globals because they are extremely hard to manage. Say a team member overrides an $ADMIN variable in a file to be 1, and then all code that references the $ADMIN variable will now have the value of 1.

globals are so PHP4, so you need to pick a better design pattern, especially if this is new code.

A way to do this without using the ugly global paradigm is to use a class container. This might be known as a "registry" to some people.

class Container {
  public static $setting = "foo";
}


echo Container::$setting;

This makes it more clear where this variable is located, however it has the weakness of not being able to dynamically set properties, because in PHP you cannot do that statically.

If you don't mind creating an object, and setting dynamic variables that way, it would work.

Upvotes: 2

You need to pass the variable as a parameter to that function to avoid using GLOBALS.

The Problematic Scenario (Works ! but avoid it at all costs)

<?php
$test = 1;
function test()
{
global $test; 
echo $test; // <--- Prints 1
}
test();  

The right way...

<?php
$test = 1;
function test($test)
{
    echo $test; // <--- Prints 1 
}
test($test); //<--- Pass the $test param here

Upvotes: 1

Related Questions