gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:57:55 25 4
gpt4 key购买 nike

是否可以在 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;
}

最佳答案

你不需要在函数的 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;
}

来自 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.

关于php - 我可以在 PHP 的函数中使用常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4131004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com