Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: global variable alternatives?

I'm working on a PHP project, and from time to time between things I read online and things I see in forums, etc. I keep reading that you shouldn't use php globals. Making sure that I don't get that mixed up with PHP register_globals, because I'm not, I have been researching, but I haven't really found why or any type of alternatives.

So, my question is simple. Should I not use the global keyword in PHP? Additionally, if I shouldn't (or should), are there any alternatives? Reason being is, I have noticed that I need to access a variable defined in another file and I need to reference or call this variable in a function, lots of functions, and I'm kind of getting tired or using the global $var_name; code so much.

Any ideas (or am I just plain wrong)?

like image 627
drewrockshard Avatar asked Aug 02 '11 22:08

drewrockshard


2 Answers

Static classes and singletons are only little better than globals. Static classes merely group global variables, but the variables themselves are still globally reachable, single instance variables. Same goes for Singletons. While they have their uses, they should not be used as a general replacement for globals. PHP makes it tempting though, especially because of having to declare global variables in functions, while static classes are available always and everywhere.

You'd best put the variables in a class (like a 'AppConfig' or more specific class), and create an instance of that class to hold specific values. Then, pass that instance to all methods in your framework. That way, you don't rely on a specific Singleton implementation, and are truly flexible.

But, I must admit that it's a lot of work, especially when you're not experienced yet. So using a singleton now is probably ok, as long as you keep this answer in mind when you feel your singletons itching somewhere in the future.

like image 162
GolezTrol Avatar answered Sep 22 '22 09:09

GolezTrol


You're not wrong, you just need to think of some architecture for your application. : )

If you have shared data between classes, you should use a model that contains that shared data and has an API accessible to all your classes to retrieve that variable.

For simplicity's sake, you can use a Singleton to contain any shared data.

The PHP Patterns Page has an example of a Singleton. The idea behind a Singleton is that you always access the same instance (version) of that class, so that if you change the variable there, it will automatically be changed elsewhere.

like image 41
citizen conn Avatar answered Sep 24 '22 09:09

citizen conn