CutCodeDown

Web Development => PHP => Topic started by: GrumpyYoungMan on 22 Feb 2021, 09:07:26 am

Title: Database Connection Global Across Functions/Files
Post by: GrumpyYoungMan on 22 Feb 2021, 09:07:26 am
I can not seem to find a definitive guide or best practice on how to make the PDO MySQL driver and connection global across functions without using global - and I know that is bad practice... so how and what is the best practice? Passing it via the function seems a bit long-winded?
Title: Re: Database Connection Global Across Functions/Files
Post by: Dave on 25 Feb 2021, 04:24:21 pm
Not sure why you think passing a PDO object is long-winded but that would be the "proper" way to do it. If you pass it to a class use __CONSTRUCT in the class to make a clone of that object for the class to use (via $this->ourdb or whatever name you use).
Title: Re: Database Connection Global Across Functions/Files
Post by: Jason Knight on 25 Feb 2021, 10:38:24 pm
connection global across functions without using global
That's because one of the entire reasons mysql_ functions went the way of the dodo and that both mysqli and PDO make objects is that it's NOT SUPPOSED TO BE GLOBAL.

It's also where object scope is handy as you can pass it to the constructor of the things that should have access.

Scope isolation is a good practice, it can be a hair more code but it maintains the separations needed to have a degree of ring security in the shit-shows that are interpreted languages.

Just like how global variables should be kept to a bare minimum and never used for anything security related. Thus why the idiots putting sql un/pass into DEFINE are complete morons.