PHP未定义变量$u LIT[“某物”]
在我的config.php中,我有以下数组:PHP未定义变量$u LIT[“某物”],php,html,arrays,Php,Html,Arrays,在我的config.php中,我有以下数组: $_LIT = array( /* Адрес сайта */ "url" => "http://learnit.loc/", // Адрес сайта .... ); 问题是,我无法在下面的代码中使用此数组: 例如,我有一个mail方法,我必须将$\u LIT[“url”]放在我的特殊链接变量中: function testMethod($username, $email) { $link = $_LIT["url"]
$_LIT = array(
/* Адрес сайта */
"url" => "http://learnit.loc/", // Адрес сайта
....
);
问题是,我无法在下面的代码中使用此数组:
例如,我有一个mail方法,我必须将$\u LIT[“url”]
放在我的特殊链接变量中:
function testMethod($username, $email) {
$link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";
}
而且。。。我不能使用它($\u LIT[“url”]
)。它只是把什么都不放,网站url应该放在哪里
我还可以说,我在ohter.php文件中使用config.php,使用“require\u once
”config.php
”。所以我可以在那里找到$\u LIT[“something”]
,但不能直接在confing.php中找到。为什么?
感谢您的帮助。无法直接访问函数范围之外的变量 您需要在函数内部使用关键字
global
如global$\u LIT
$link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";
链接到文档
----更新----
要在函数或类范围内使用全局变量,需要使用
global
关键字:
function testMethod($username, $email) {
global $_LIT;
$link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";
}
更多信息请参见。函数范围外声明了$\u LIT变量。通过将其声明为全局,可以在函数范围内访问它,如下所示:
function testMethod($username, $email)
{
global $_LIT;
$link = $_LIT['url'];
}
另一种方法是添加$_LIT变量作为函数的依赖项;这允许您在将来很容易地改变函数的行为,例如,如果您需要提供本地化
function testMethod($username, $email, $config)
{
$link = $config['url'];
}
然后调用函数,如下所示:
testMethod('username', 'email', $_LIT);
因为
$\u LIT
不在您的功能范围内。阅读PHP手册中有关作用域的更多信息。您说过您将此变量放置在config
中,并且config
始终在任何地方都可用,或者必须有加载config
的方法。你在用什么框架吗?是的。但是现在有一个错误(global$_LIT[“url”];):语法错误,意外的“[”,期望的“,”或“;”,您也可以将其作为函数中的参数。实际上,它应该是global$_LIT;
,但global是丑陋的
testMethod('username', 'email', $_LIT);