Jeremy
Jeremy

Reputation: 582

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 '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

Answers (4)

Haim Evgi
Haim Evgi

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

alex
alex

Reputation: 490143

define() produces global constants.

There are much better ways to store config items.

Upvotes: 3

theazureshadow
theazureshadow

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

netcoder
netcoder

Reputation: 67695

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.

Upvotes: 4

Related Questions