PHP GLOBALS 错误
我正在尝试将数组存储在 PHP GLOBAL 中,如下所示:
// file_1.php
include 'functions/session_metrics.php';
$project_data = array();
$session_data = array();
if (isset($_GET["product"])) {
$product = explode("|", $_GET["product"]);
foreach ($product as $id) {
list($project, $sessions) = getProductInfo( $id );
$project_data[$id] = $project;
$session_data[$id] = $sessions;
}
$GLOBALS['project_data'] = $project_data;
$GLOBALS['session_data'] = $session_data;
}
现在从 另一个文件 我正尝试像这样退休它:
// file_2.php
$data= $GLOBALS['project_data'];
print_r($data);
但我看到错误:
Undefined Index: project_data...
我缺少什么?
I'm trying to store an array in a PHP GLOBAL like so:
// file_1.php
include 'functions/session_metrics.php';
$project_data = array();
$session_data = array();
if (isset($_GET["product"])) {
$product = explode("|", $_GET["product"]);
foreach ($product as $id) {
list($project, $sessions) = getProductInfo( $id );
$project_data[$id] = $project;
$session_data[$id] = $sessions;
}
$GLOBALS['project_data'] = $project_data;
$GLOBALS['session_data'] = $session_data;
}
Now from another file I'm trying to retireve it like so:
// file_2.php
$data= $GLOBALS['project_data'];
print_r($data);
But I see the error:
Undefined Index: project_data...
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不直接使用本机 php
$_SESSION
来存储会话数据:同样通过这样做:
$GLOBALS['session_data'] = $session_data;
您设置的值等于本身(这是隐式的)除非$session_data
位于函数内部。Why not just use native php
$_SESSION
to store session data:Also by doing this:
$GLOBALS['session_data'] = $session_data;
you are setting a value equal to itself (which is implicit) unless$session_data
is inside of a function.大多数时候,您必须将数据传递到另一个文件,就像将数据传递到当前文件一样。
因此,如果您对 file_1.php 使用 GET,很可能您需要将相同的参数传递给 file_2.php。
这是更常见的方式,与用途非常有限的会话不同。
Most of time you have to pass the data to another file the same way you passed it into current.
So, if you use GET for the file_1.php, most likely you will need to pass the same parameter to the file_2.php.
It is way more common way, unlike sessions which have very limited use.
另一个文件没有看到“session_data”变量。此外,使用这样的全局变量是非常危险的,这就是为什么 PHP 从 PHP 5.4 开始将其从语言中完全删除,并在 PHP 5.3 中弃用。
如上所述,您应该使用 $_SESSION 变量将信息从一个文件传递到另一个文件。
您可以通过以下方式执行此操作:
The other file is not seeing the 'session_data' variable. Also it is very risky using globals like that, which is why PHP has completely dropped it out of their language as of PHP 5.4 and have it deprecated in PHP 5.3.
As stated above, you should use the $_SESSION variable to pass info from one file to another.
You can do so by: