我可以在PHP中的函数中使用常量吗?

Jer*_*emy 21 php constants

是否可以在PHP函数中使用PHP常量?

// 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;
}
Run Code Online (Sandbox Code Playgroud)

Hai*_*vgi 22

您不需要global在函数中声明它们,PHP将它们识别为全局变量.

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;
}
Run Code Online (Sandbox Code Playgroud)

来自php.net:

像超长球一样,常数的范围是全局的.您可以在脚本中的任何位置访问常量,而不考虑范围.有关范围的更多信息,请阅读有关变量范围的手册部分.

  • 刚刚赞成你的回答,但是想指出*php将它们识别为超级全局.*应该是*php将它们识别为全局.* (2认同)