Can I use constants within functions in PHP?
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 'gl开发者_StackOverflow社区obal' 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;
}
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.
Have you at least tried it? :)
From the manual:
Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope.
define()
produces global constants.
There are much better ways to store config items.
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.
精彩评论