Jump to content

including functions & db connections


phpnewby1918

Recommended Posts

Hi,

 

Just a quick query.

 

I call my db connection and configuration files on every script.

I also have just made a functions script where i'm storing some functions

except when i call the function, my script fails because of a missing database connection.

 

But on the page that fails, i call the configuration files including the db connection at the start of the script.

 

But when i get to where i include the function they are all on the same script so should it fail??

 

The page did work fine when the function was inbedded in the script. But as i'm using the function on a few pages, i thought it would be better practise and more efficent to just include the function on each page i need, rather than just copy and paste all the php in the required pages.

 

Or do i have to declare the db connection inside the function page as well???

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/225994-including-functions-db-connections/
Share on other sites

The database variable is not in the scope of the function--it needs to be.  Google php scope for more info on that.

 

So you either have to make the database variable global, or use dependency-injection (meaning, pass the database variable as a parameter to each function).  The latter is more pro.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.