0

I've got a $db variable (and others) in my global config and I've seen some sample code recently like:

function getInfo(\My\Namespace\DB $db) {...} and then calling getInfo($db);

but I'm used to just doing:

function getInfo() {
 global $db;
 ...
}

What's the difference and is one better/preferred/best practice compared to the other now?

Thanks.

Andrew T
  • 319
  • 2
  • 12
  • [suggested reading](https://www.php.net/manual/en/language.namespaces.rationale.php) – jibsteroos Mar 05 '21 at 21:10
  • `function getInfo(\My\Namespace\DB $db)` is called "dependency injection" adn would be the preferred way (even though you should type hint interfaces, not specific implementations.) This allows you to pass in the implementation you want in that moment (like if you would need two different db-connections at the same time). It also makes it easier to test the function since you can pass in a mock instead of the real db-class. – Magnus Eriksson Mar 05 '21 at 21:10
  • Also, if you keep everything in the global namespace, there's a bigger risk to accidentally overwrite variables, which could give you issues that's very hard to debug. – Magnus Eriksson Mar 05 '21 at 21:12

0 Answers0