[英]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
未在頂層聲明,但在f1
和f2
中聲明為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.