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; }
Yes, but you don't need to call them "global". Constants are global.
You can use the const keyword to declare constants globally in PHP. All you need to do is ensure that it is declared outside of a namespace or class. With the example below, you can see that our “ WEBSITE ” constant is still accessible from within the “ bar() ” function.
To create a constant, use the define() function.
Constants cannot be defined by simple assignment, they may only be defined using the define() function. Constants may be defined and accessed anywhere without regard to variable scoping rules. Once the Constants have been set, may not be redefined or undefined.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With