Reputation: 582
Is it possible to use a PHP constant within a PHP function?
// in a different file
DEFINE ('HOST', 'hostname');
DEFINE ('USER', 'username');
DEFINE ('PASSWORD', 'password');
DEFINE ('NAME', 'dbname');
// connecting to database
function database()
{
// using 'global' to define what variables to allow
global $connection, HOST, USER, PASSWORD, NAME;
$connection = new mysqli(HOST, USER, PASSWORD, NAME)
or die ('Sorry, Cannot Connect');
return $connection;
}
Upvotes: 24
Views: 21582
Reputation: 125446
You don't need to declare them in global
in the function, PHP recognises them as globals.
function database()
{
// using 'global' to define what variables to allow
global $dbc;
$connection = new mysqli(HOST, USER, PASSWORD, NAME)
or die ('Sorry, Cannot Connect');
return $connection;
}
From php.net:
Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.
Upvotes: 23
Reputation: 490143
define()
produces global constants.
There are much better ways to store config items.
Upvotes: 3
Reputation: 10049
Yes, but you don't need to call them "global". Constants are global. If you get unexpected T_STRING, expecting T_VARIABLE
as an error, it's because it doesn't expect to see the constant references after a "global" statement.
Upvotes: 1