3

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

markmb
  • 802
  • 1
  • 12
  • 31
  • 4
    Don't use globals. Ever. –  Feb 09 '13 at 23:01
  • Are they unsecure? Or what is the problem with them? – markmb Feb 09 '13 at 23:03
  • 2
    They can be unsecure. But my (and most other peoples) problem with them is how they make code really hard to read/understand. So try to avoid them, please. –  Feb 09 '13 at 23:05
  • 1
    And when passing a ressource to a function, PHP always passes it by reference (passing it by value has no meaning), so you don't have to force passing it by reference. – tmuguet Feb 09 '13 at 23:11

2 Answers2

1

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:

  • Is basically an hack to introduce a global variable (instance), therefore inheriting the problems from globals.
  • Goes against the Single responsibility principle.
  • Hide program's dependencies
  • Is hard to unit test

Here you can find some references:

Community
  • 1
  • 1
Shoe
  • 70,092
  • 30
  • 150
  • 251
  • Then, I'm gona get used to pass mysqli resources by parameter and avoiding globals. I just wanted to know opinions, to start with my first "big" project. Thanks – markmb Feb 09 '13 at 23:49
0

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.

Your Common Sense
  • 152,517
  • 33
  • 193
  • 313