MargateSteve Posted November 24, 2013 Share Posted November 24, 2013 I have recently started venturing in to creating re-usable functions and, as per the tutorials I read up on, have liberally used global. Since starting this, I have started seeing virtually everywhere that this is a bad idea so now am left with around 50 functions that are apparently bad practice! Fortunately all of these are currently in the backend of the site so whatever problems or security risks they cause will be limited to three trusted people. So, before I move onto writing more functions, how would I go about replacing 'global' everywhere? Just to give a rough idea, most of my functions contain 3 'global's, 1 to get the database connection, 1 to create a mysql-friendly timestamp so I can use a small variable for update times etc. and at least 1 to grab a url variable. These are just examples and there may be a few other similar bits and pieces plus some other variables. Say for example I currently have these three globals at the start of my function...... global $con; global $stamp; global $getcomp;and they relate to the following outside of the function //Datebase connection $hostname_mfc = "localhost"; $database_mfc = "xx"; $username_mfc = "xx"; $password_mfc = "xx; $con = mysqli_connect($hostname_mfc, $username_mfc, $password_mfc, $database_mfc); //Simple datestamp variable $stamp = date('Y-m-d H:i:s'); //Get the comp ID from the URL $getcomp= $_GET['comp'];would I simply need to replace the section of the function on the first codeblock with that in the second? It seems a bit silly to need to write the whole database connection in each function so guess that there must be a way around this. Thanks in advance Steve Link to comment https://forums.phpfreaks.com/topic/284227-replacing-global-in-functions/ Share on other sites More sharing options...
objnoob Posted November 24, 2013 Share Posted November 24, 2013 Whatever the function needs to do it's functioning should be passed into the function as arguments. function doThis(mysqli $db, $datetime, $url){ // NOTHING FROM GLOBAL $db->query('SELECT \' ' . $db->real_escape_string($datetime) .'\'' ); } $thisDid = doThis($conn, $stamp, $url); # we pass everything the function needs to do whatever. this make doing whatever really reusable. Link to comment https://forums.phpfreaks.com/topic/284227-replacing-global-in-functions/#findComment-1459857 Share on other sites More sharing options...
MargateSteve Posted November 24, 2013 Author Share Posted November 24, 2013 Thanks objnoob. I never realised it would be that simple! Steve Link to comment https://forums.phpfreaks.com/topic/284227-replacing-global-in-functions/#findComment-1459866 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.