在我的temp_file.php中,我有一个变量(数组)
<?php
$temp = array();
?>
在我的currentPage.php中没有,我正在使用这个
<?PHP
include 'temp_file.php';
///giving some value to $id and calling same page again
array_push($GLOBALS['temp'],$id);
?>
我想在每次调用同一个文件(CurrentPage.php)时使用这个临时数组来附加一个值,但包含"temp_file.php"语句每次都在执行,并且我正在向上次被推送的数组中获取单个元素。
有人能帮我吗?php中有没有任何方法可以从第二次跳过这个include语句,直到会话结束。
由于您在问题中提到会话,您必须了解它们。那么,为什么不在会话中存储$temp
变量呢,比如:$_SESSION['temp'] = $temp
?
这就是您所需要的?
<?PHP
session_start();
if (!isset($_SESSION['temp']) {
$_SESSION['temp'] = array($id);
} else {
$_SESSION['temp'][] = $id;
}
$f = array_count_values($_SESSION['temp']);
if ($f[$id] < $Limit) {
include 'temp_file.php';
} else {
// Error
}
?>
您可以将数组存储在$_SESSION中,因此您的temp_file.php将变为:
<?php
if(!$_SESSION['temp']) {
$_SESSION['temp'] = array();
}
?>
和你的当前页面是这样的:
<?php
include 'temp_file.php';
array_push($_SESSION['temp'],$id);
?>
当会话结束时,您必须小心销毁会话变量。
没有一个答案是正确的
include_once()
对您不起作用,因为您将再次加载页面,即使是第二次,每次加载时php
都将从顶部执行。
因为include_once()
只会停止相同执行中的冗余包含,而不会停止multiple。
以下是解决问题的简单方法
<?PHP
if(!isset($_SESSION['include']) || !$_SESSION['included'])) {
// ^ Check if it was included before, if not then include it
include 'temp_file.php';
$_SESSION['included'] = true; //set a session so that this part never runs again for the active user session
}
///giving some value to $id and calling same page again
array_push($GLOBALS['temp'],$id);
?>
<?PHP
if (!isset($GLOBALS['included_temp_file']) || $GLOBALS['included_temp_file'] != true) {
include_once 'temp_file.php';
$GLOBALS['included_temp_file'] = true;
}
///giving some value to $id and calling same page again
array_push($GLOBALS['temp'],$id);
?>