Reputation: 892
Which method is better to pass a MySQLi resource to the functions on a page? As a parameter by value? As a parameter by reference? making it global?
I've been thinking on this for a while, and I don't know which is better or how to look it.
Thanks in advance
Upvotes: 3
Views: 364
Reputation: 157880
Global for sure.
You are going to pollute your code with useless extra parameter just for nothing.
Look, most people just learn some rules by heart, and follow them unconditionally. But it is better to understand their meaning and use wisely, depends on the context.
There is nothing wrong in calling a cat a cat. Yet nothing wrong in calling global variable a global.
Although "globals are generally considered a bad practice", this case is different.
It is indeed a bad practice when you're using global
keyword to pass local variables. It makes your code obscure and hard to support - I am not arguing that.
But a true global variable is a completely different matter. PHP is using them all the way - a $_SERVER
array is a perfect example.
So, for a really global variable, which is used all the way throughout your code and being the part of documented API - global
is the best choice.
Upvotes: 0
Reputation: 76280
The pattern that most people suggest is to pass it via parameter's function or use Dependency Injection if you are coding the OOP way.
Globals are generally considered a bad practice because they make it hard to read the code and detect the dependencies.
It's right for you to know that there's another option, but has been the subject of criticism around the web: the Singleton design pattern. The biggest problems about it are:
Here you can find some references:
Upvotes: 1