简体   繁体   English

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

[英]Can I use constants within functions in PHP?

Is it possible to use a PHP constant within a PHP function? 是否可以在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;
}

You don't need to declare them in global in the function, PHP recognises them as globals. 您不需要在函数的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;
}

From php.net: 来自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. define()生成全局常量。

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. 如果你得到unexpected T_STRING, expecting T_VARIABLE是一个错误,那是因为它不希望在“全局”语句之后看到常量引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM