简体   繁体   English

PHP 变量生命周期

[英]PHP variable life cycle

Ok I'm trying to pass a variable, but I have a problem.好的,我正在尝试传递一个变量,但是我遇到了问题。 All happens in one PHP file, and simplified code is like this:一切都发生在一个 PHP 文件中,简化后的代码是这样的:

    <?php session_start(); ?>
    <html>
                ...some HTML code...
    <?php
          $var = 100      // variable that i need
          $_SESSION['passover'] = $var; 

     ?>                

     ...HTML code with 'submit' form 
      </html>

     <?php
      if(isset($_POST['submit'])){..do something...}
      $var_again = $_SESSION['passover']   //problem!
      print_r($_SESSION);  

      session_destroy();  
      ?>

Before I press submit I get output like: Array ( [passover] => dog.jpg ) After I press submit I get: Array ( )在按下提交之前,我得到如下输出: Array ( [passover] => dog.jpg ) 按下提交后,我得到: Array ( )

What am I doing wrong?我究竟做错了什么? In this case variable is a file name, but I;ve tried with simple numbers and it won't work either.在这种情况下,变量是一个文件名,但我已经尝试过使用简单的数字,但它也不起作用。

You need to remove session_destroy from code, follow this logic:您需要从代码中删除 session_destroy,请遵循以下逻辑:

  1. You start session (ok)你开始会话(好的)
  2. you put variable into session (ok)你把变量放入会话(好的)
  3. you print variable from session (ok)你从会话中打印变量(好的)
  4. you deleted all information from session (not ok)您从会话中删除了所有信息(不行)
  5. on next request (after submit) you have empty session, because of p4在下一个请求(提交后)你有空会话,因为 p4

Session_destroy() is definitely the culprit. Session_destroy() 绝对是罪魁祸首。
Also, I imagine you left a couple semicolons out of your sample code by accident, but the semicolon is missing twice ..另外,我想您不小心在示例代码中留下了几个分号,但是分号丢失了两次..

$var = 100  **;**    // variable that i need
.
.
$var_again = $_SESSION['passover'] **;**  //problem!

Plus, you actually used two variable names there: $var and $var_again.另外,您实际上在那里使用了两个变量名:$var 和 $var_again。 If that's both meant to be the same thing, this could be a problem, too.如果这两者是同一件事,那么这也可能是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM