Jump to content

Replacing global in functions


MargateSteve

Recommended Posts

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

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.

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.