MargateSteve Posted November 24, 2013 Share Posted November 24, 2013 (edited) 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 Edited November 24, 2013 by MargateSteve Quote Link to comment Share on other sites More sharing options...
Solution objnoob Posted November 24, 2013 Solution 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. Quote Link to comment 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.