Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP best practices: repass variables from config file when calling functions or use global?

I have a program that I use on several sites. It uses require('config.php'); to set any site dependant variables like mysql connect info, paths, etc.

Let's say that I use one of these site-dependant variables in a function, like $backup_path.

This variable was initially declared in config.php, and does not appear in the main program file.

I need to access this variable in function makebackup($table_name); (also in a separate functions.php file).

Is it better to say

makebackup('my_table');

and then use "global $backup_path" inside the function, or is it better to call the function using

makebackup('my_table',$backup_path);

The argument for the first is that it keeps the main program flow simple and easy to understand, without clutter.

The argument for the second is that it might not be obvious that the variable $backup_path exists after some time has passed, and debugging or reworking could be difficult.

Is one or the other of these techniques "standard" among professional programmers? Or should I be using $_SESSION to declare these global variables?

like image 932
Andrew Swift Avatar asked Sep 18 '09 09:09

Andrew Swift


2 Answers

The second alternative,

makebackup('my_table', $backup_path);

is a reusable function and therefore generally preferable. The extra argument is not a big price for reusability.

If you are entirely sure that you'll ever use that function in that particular application only, and for $backup_path only, then maybe consider the global alternative. Even then it's good to check that the global variable actually exists. And be aware that it's extremely difficult to get rid of globals once you start using them.

like image 111
Joonas Pulakka Avatar answered Oct 19 '22 18:10

Joonas Pulakka


Remember that you can set a default value for your function:

function makebackup($table, $dir = CONFIG_BACKUP_PATH)

That way you won't have to supply the variable in the default case, you can simply assume that the configured backup path is the default.

This assumes that you are using constants, not global variables.

like image 29
Vegard Larsen Avatar answered Oct 19 '22 18:10

Vegard Larsen