PHP中无法访问变量

时间:2013-03-21 20:18:30

标签: php variables

我有一个名为file_with_data_from_server.php的文件,它会从$_POST['data]来电中接收AJAX。我设法创建一个新数组来包含来自服务器的数据。然后,此file_with_data_from_server.php包含在另一个.php文件中。当然,file_with_data_from_server.php上存在的所有变量都可以在包含它的文件中访问,但在我的情况下,我无法访问变量,其值取自json_decoded数据。这是file_with_data_from_server.php上的代码,

        $data_for_reports = $_POST['data']; // data from server

        $rrow = json_decode($data_for_reports);
        $dates_for_reports = array();
        foreach($rrow as $rr){
            $dates_for_reports[] = $rr->time_period;
        }
        $current_date_with_data = end($dates_for_reports);      // this contains data like '201301'

在我的.php文件中,我包含file_with_data_from_server.php,我有这段代码,

        include('file_with_data_from_server.php');
        echo '<pre>';
            print_r('test'.$current_date_with_data);
        echo '</pre>';

我正在尝试打印$current_date_with_data变量的值,但它什么也没显示。

2 个答案:

答案 0 :(得分:1)

从我可以收集的内容中,您将file_with_data_from_server.php包含在另一个PHP脚本(以下简称other.php)中并发布到file_with_data_from_server.php,期望变量以{{1}打印}}。这是行不通的,因为实际上other.php实际上并没有被调用。

考虑一下:

<强> a.php只会

other.php

<强> b.php

$myVar = $_POST;

如果你发帖到include('a.php'); var_dump($myVar); - a.php从未被调用过!在这种情况下,b.phpinclude永远不会被执行,因为只调用了var_dump

但是,有了上述内容,如果您要发布到a.php(包括b.php),这可能会像您预期的那样发挥作用。

答案 1 :(得分:1)

print_r()来电输出"test"吗?可能$current_date_with_data包含null或某些不符合任何字符串的内容。

这是检查您定义的每个变量的简单方法:

echo "<pre>";
echo HtmlSpecialChars(print_r($GLOBALS, true));
echo "</pre>";

<强>更新

听起来juco找到了你的解决方案。您实际上并未将数据发布到第二个php文件中。数据仅在初始帖子中提供给file_with_data_from_server.php,而不是后续请求。

如果您需要在一个请求中发送数据并在稍后的另一个请求中访问它,则需要将数据存储在某个地方,例如会话变量或数据库中。

PHP中的每个请求都是新的,并且不包含先前请求中的数据。这被称为“无国籍”。 Google有很多结果可以解释网络应用中的无状态问题。

http://www.phpfreaks.com/tutorial/sessions-and-cookies-adding-state-to-a-stateless-protocol