PHP未定义变量$_LIT[“something”]


PHP Undefined variable $_LIT["something"]

在我的config.php中,我有一个数组:

$_LIT = array(
    /* Адрес сайта */
    "url" => "http://learnit.loc/", // Адрес сайта
....
);

问题是,我不能在下面的代码中使用这个数组:

例如,我有一个mail方法,我必须将$_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";
}

而且。。。我不能用它($_LIT["url"])。它只是什么都不放,网站网址应该在哪里。

我还可以说,我使用"require_once"config.php"在ohter.php文件中使用config.php。所以我可以在那里获得$_LIT["something"],但不能直接在confing.php中获得。为什么?

谢谢你的帮助。

不能直接访问函数范围之外的变量。

您需要在函数中使用关键字global

global $_LIT

$link = $_LIT["url"]."scipts/activate.php?link=".rand(0, 999999).rand(0, 999999).rand(0, 999999).rand(0, 999999).$username."activationLink";

链接到文档。

http://php.net/manual/en/language.variables.scope.php

----更新----

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";
}

要在函数或类范围内使用全局变量,需要使用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";
}

更多信息,请参阅文档。

$_LIT变量是在函数范围之外声明的。您可以在函数范围内通过将其声明为全局来访问它,如下所示:
function testMethod($username, $email)
{
    global $_LIT;
    $link = $_LIT['url'];
}

另一种方法是添加$_LIT变量作为函数的依赖项;这允许您在将来轻松地更改函数的行为,例如,如果您需要提供本地化。

function testMethod($username, $email, $config)
{
    $link = $config['url'];
}

然后调用这样的函数:

testMethod('username', 'email', $_LIT);