Using variables in a PHP function

Ok, so I've got three files.. for example purposes: config.php, functions.php and index.php

In config.php I have all the variables needed for the site to work, settings, db details, etc. In functions.php, the function I'm trying to get to work is as follows:

function db_connect() {
    mysql_connect($app_config['mysql_server'], $app_config['mysql_username'], $app_config['mysql_password']) or db_die(__FILE__, __LINE__, mysql_error());
    mysql_select_db($app_config['mysql_database']) or db_die(__FILE__, __LINE__, mysql_error());

}

What this should be referencing, is variables set in config.php, eg:

$app_config['mysql_username'] = "root";
$app_config['mysql_password'] = "password";

Both config.php and functions.php are required in index.php, which uses the function, but in the PHP error log I get the following (more than once for the different instances):

[Mon May 28 02:02:46 2012] [error] [client <removed>] PHP Notice:  Undefined variable: app_config in /usr/home/<removed>/functions.php on line 11

I even tried including config.php in functions.php too, but to no avail. Any ideas as to why this isn't working? I'm sure it's relatively simple, but I just can't fathom it..

Answers


two options: by contract or global variables

function db_connect() {
    global $app_config;
    mysql_connect($app_config['mysql_server'], $app_config['mysql_username'], $app_config['mysql_password']) or db_die(__FILE__, __LINE__, mysql_error());
    mysql_select_db($app_config['mysql_database']) or db_die(__FILE__, __LINE__, mysql_error());
}

// contract
function db_connect(array $app_config) {        
    mysql_connect($app_config['mysql_server'], $app_config['mysql_username'], $app_config['mysql_password']) or db_die(__FILE__, __LINE__, mysql_error());
    mysql_select_db($app_config['mysql_database']) or db_die(__FILE__, __LINE__, mysql_error());
}

although you could do something more "elegant" and create a class


global $app_config, you want to put that in the function, before using anything from that variable

That basically says retrieve the $app_config variable from the global namespace for use in this function. PHP globals, although available to all functions, are not involved in that function's namespace until you explicitly ask it to be. That's what's happening for you, you're using the variable before you've 'asked' for it.


Need Your Help

How to terminate non-blocking socket connection attempt?

c linux sockets connect nonblocking

A typical answer to the question of how to put time limit on connection attempt when using sockets is this:

ld: library not found for -lintl on mac os x lion

git install

I installed git 1.7.4.4 long time ago.