更改全局变量并从另一个.php文件获得更改的值


Change global variable and get changed value from another .php file

我试图用按钮改变背景颜色,我可以这样做,但是如果我改变页面,我无法得到变量的改变值。也许这是一个愚蠢的方法;我不知道,但我希望它不是。

home-featured-fullwidth.php:

<?php
global $arka;
$arka = 'wall2';
$button = 'button2';
if (isset($_POST['button2'])) {
    $arka = "wall";
    $button = 'button1';
}
if (isset($_POST['button1'])) {
    $arka = "wall2";
    $button = 'button2';
}
echo '<div class="home-featured-full ' . $arka . '">';?>
// codes and close </div>
<form class="padding" method="POST" action=''>
    <?php echo '<input id="iki" type="submit" name="' . $button . '"  value="Change BackGround">'; ?>
</form>

single-video-fullwidth.php:

<?php 
echo '<div class="' . $arka . ' full-width-video-layout">' ?>codes and close </div>

希望你能帮忙。

HTTP是一种无状态协议,PHP实现并没有尝试解决这个问题。这意味着,全局变量在设计上只对单个请求是全局的。

简而言之:一个PHP请求中的变量通常不会在另一个PHP请求中可用。

由于您的场景非常常见,因此存在sessions的构造,它允许您"在会话中"存储变量并在以后的请求中检索它。阅读PHP会话,它们很容易使用,并且对于单服务器使用来说足够好。

创建一个文件:

<? PHP session_start();
echo "this is the first file";
$_SESSION['global'] = "From the first file";
?>

创建另一个文件:

<? PHP session_start();
echo "this is the second file";
if(@isset($_SESSION['global'])){
    echo $_SESSION['global'];
}
?>