从php中的多个文件中访问一个文件中声明的更新变量


Accessing a updated variable declared in a file from multiple files in php

我在php文件中声明了一个变量数组,并在包含该文件后更改了该数组的值。然后,在更改之后,我希望数组变量具有更新的值,这样如果我从第三个文件访问它,我将获得新的数组值。我该怎么做呢?我需要它从一个在线测验页面。每当用户从数据库加载页面时,我都会获取随机问题。提交后,为了显示结果,我需要在submit.php页面(提交后重定向的页面)中获取的问题的id号。我已经将问题id存储在问题页面的一个数组中,并且我希望可以从submit.php页面访问该数组。

这取决于你希望数组的行为。

如果它是一个特定于某人浏览你的web应用程序的实例的数组,其中每个人都有他们自己的变量来做他们喜欢的事情,那么你可能想要使用sessions和$_SESSION全局变量来设置它。也许像这样:

//file1.php
<?php
    session_name("applicationName"); //give your session a unique and static name, so that other apps on your server don't interfere
    session_start(); //must always start the session before working with session variables
    $_SESSION['data'] = array(1, 3, 6, 9); //set your array into the session global
    include("file2.php");
?>
//file2.php
<?php
    $_SESSION['data'][0]++; //for demonstration purposes, increment the first key of the array
?>
//file3.php
<?php
    session_name("applicationName"); //same session name
    session_start();
    print_r($_SESSION['data']); //shows the contents of your array,
        //which will now contain 2, 3, 6, 9
?>

然而,如果数组中的数据应该被任何访问你的应用程序的人全局访问,你可能想要考虑使用数据库或APC来存储你的数组。简单使用平面文件的危险在于,一个用户可能执行写操作,而另一个用户执行读操作,这可能导致不可预测的结果。像MySQL这样的数据库和像APC这样的缓存扩展主要是基于先到先得的基础上运行的,并且不会受到这个问题的影响。

如果您的数据很重要,请使用数据库,因为数据将在服务器重启后存活:

//store the variable to a row in the database
$query = $dbconn->query("INSERT INTO tblVariables(variableName, variableValue)
    VALUES ('someVariable', '".$dbconn->real_escape_string(serialize($yourArray))."';");
//retrieve the variable from that row
$query = $dbconn->query("SELECT variableValue FROM tblVariables WHERE variableName = 'someVariable';");
if($query) {
    while($row = $query->fetch_assoc())
        $yourArray = deserialize($row['variableValue']);
}

serialize()/deserialize()是将数组或对象合并为单个可存储字符串的方便方法。确保存储它的数据库列是足够大的VARCHARTEXT

如果你的数据本质上是临时的,APC可以做到这一点,只要它在你的服务器上可用:

//store the array in APC
apc_store('variableName', $yourArray);
//retrieve the array from APC
$yourArray = apc_fetch('variableName');

APC不要求你使用serialize() .

您必须弄清楚数据库或APC在应用程序中的位置,但是会话示例应该足以让您了解如何根据您的问题组织代码。