簡體   English   中英

PHP 全局變量是 function 內部的 null,但外部不是 Z37A6259CC0C1DAE299A78668

[英]PHP global variable is null inside a function, but is not null outside it

我遇到了一個錯誤,全局似乎無法正常工作並且無法訪問變量。

這是我的代碼:

function getComments($id)
{
    global $conn;
    $COMPONENT_NAME = "view_company_comments";
    include_once "validateUser.php";

只是為了上下文,如果COMPONENT_NAME不會出現在某個定義的列表中,腳本執行將停止使用 die() function。

現在在“validateUser.php”中:

(在評論中解釋了一切)

   <?php

   if (!isset($COMPONENT_NAME)) {
        die(json_encode(["error" => "validating user: component was not set."]));
    } else {

        include_once "permissions.php";
        $validateUser_allowedActions = permissionsInitActions();

        //So far in, var_dump($COMPONENT_NAME) works properly here, and I get the component name succesfully. 
        //But watch next:

        //"permissionsAllowed()" is a function from "permissions.php", 
        //this function returns "false" here, expected result is "true"

        if (!permissionsAllowed($validateUser_allowedActions)) {
            die(json_encode(["error" => $COMPONENT_NAME . ": Unvalidated user privillege."]));
        }
    }

在“permissions.php”中:

function permissionsAllowed($actions)
{
    global $COMPONENT_NAME, $conn;

    //Here, var_dump($COMPONENT_NAME) results to "null", which is weird
    //because in "validateUser.php" it is a correct string value.

    $sql = "SELECT id FROM permission_actions WHERE `name` = '$COMPONENT_NAME'";
    $result = mysqli_query($conn, $sql);
    $actionID = mysqli_fetch_assoc($result)["id"];
    var_dump($COMPONENT_NAME);

    if (in_array($actionID, $actions)) {
        return true;
    }
    return false;
}

這里發生了什么? 我錯過了什么?

謝謝你的幫助。

$COMPONENT_NAME不是getComments中的全局變量。 盡管您已在permissionsAllowed中將其聲明為global ,但在getComments中並未將其聲明為global ,因此getComments中的$COMPONENT_NAME是 scope 的本地變量,因此無法通過permissionsAllowed中的global $COMPONENT_NAME看到。

考慮以下代碼(演示):

$b = 5;

function f1 () {
    global $a;
    $a = 4;
    $b = 3;
    $c = 2;
    f2();
}

function f2 () {
    global $a, $b, $c;
    var_dump($a);
    var_dump($b);
    var_dump($c);
}

f1();

Output:

int(4)
int(5)
NULL

$a未在頂層聲明,但在f1f2中聲明為global - 在f1中對其進行的修改可以在f2中看到。
$b在頂層聲明,但僅在f2中聲明為global f1中的$b是 scope 本地的,對其進行的更改對f2中的$b沒有影響。
$c未在頂層聲明,僅在f2中是global的。 同樣, f1中的$c是 scope 的本地變量,對其進行更改對f2中的$c沒有影響,因此f2中引用的global $c沒有任何價值( null ),因為它沒有在任何地方設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM