Mysqli resource in PHP as parameter or global

What is the best method to pass to the MySQLi resource for the functions on the page? How is the parameter by value? How is the parameter on the link? what makes it global?

I have been thinking about this for a while and I don't know which is better or what it looks like.

Thank you in advance

+3


source to share


2 answers


The pattern most people suggest is to pass it through a parameter function, or use dependency injection if you're coding the OOP way.

Globals are generally considered bad practice because they make it difficult to read your code and find dependencies.

It's right for you to know that there is another option, but has been the subject of criticism on the internet: the Singleton design pattern. The biggest problems:



  • It is basically a hack to represent a global variable (instance), so inherits problems from global variables.
  • Goes against the principle of single responsibility.
  • Hide software dependencies
  • Difficult unit test

You can find several links here:

+1


source


Global.

You are about to pollute your code with a useless extra parameter. Look, most people just learn some rules by heart and follow them unconditionally. But understanding their meaning better and using them wisely depends on the context.



There is nothing wrong with calling a cat a cat. But there is nothing wrong with calling a global variable globally. While globals are generally considered bad practice, this case is different. It's a really bad experience when you use the keyword global

to pass local variables. This makes your code obscure and difficult to maintain - I don't argue. But a true global variable is a completely different matter. PHP makes full use of them - an array $_SERVER

is a great example.

So, for a truly global variable that is used throughout all of your code and is part of the documented API global

, is the best choice.

0


source







All Articles