Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use constants within functions in PHP?

Tags:

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; } 
like image 482
Jeremy Avatar asked Nov 09 '10 06:11

Jeremy


People also ask

Can constants be in function?

Yes, but you don't need to call them "global". Constants are global.

Can you use const in PHP?

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.

Which functions is used to declare constants in PHP?

To create a constant, use the define() function.

Which is not a rule for defining constants in PHP?

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.


Video Answer


2 Answers

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.

like image 88
Haim Evgi Avatar answered Oct 03 '22 10:10

Haim Evgi


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.

like image 28
netcoder Avatar answered Oct 03 '22 12:10

netcoder