CUTCODEDOWN
Minimalist Semantic Markup

Welcome Guest
Please Login or Register

If you have registered but not recieved your activation e-mail in a reasonable amount of time, or have issues with using the registration form, please use our Contact Form for assistance. Include both your username and the e-mail you tried to register with.

Author Topic: Database Connection Global Across Functions/Files  (Read 521 times)

GrumpyYoungMan

  • Hero Member
  • *****
  • Posts: 792
  • Karma: +8/-0
    • Grumpy Young Man
Database Connection Global Across Functions/Files
« 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?
Trying to learn a new trick to prove old dogs can learn new ones...

Total Novice have-a go Amateur Programmer - not sure that is the right thing to say... but trying to learn...

Dave

  • Junior Member
  • *
  • Posts: 38
  • Karma: +12/-0
Re: Database Connection Global Across Functions/Files
« Reply #1 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).
Dave

Jason Knight

  • Administrator
  • Hero Member
  • *****
  • Posts: 1054
  • Karma: +188/-1
    • CutCodeDown -- Minimalist Semantic Markup
Re: Database Connection Global Across Functions/Files
« Reply #2 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.
We are all, we are all, we are all FRIENDS! For today we're all brothers, tonight we're all friends. Our moment of peace in a war that never ends.

 

SMF spam blocked by CleanTalk

Advertisement