PHP static variables across multiple .php pages

我的未来我决定 提交于 2019-12-24 11:34:39

问题


I am building a POP3 mailbox in PHP. I have the following files:

  • server_access.php (fetch mails from the POP3 server)
  • data_access.php (which fetches/writes mails to local DB)
  • mime_parser.php (parses MIME content)
  • core.php (uses above files and stores parsed mail as an assoc array called $inbox)

Now, I have the pages mailbox.php to show the inbox and showmail.php to display each mail. The user's credentials are stored in a .ini file and used as necessary. The thing is, I do a require_once('core.php') in both mailbox.php and in showmail.php

I am able to display the inbox (ie. $inbox has values), however, if i select to read a mail (pop-up window of showmail.php), the $inbox is an empty array.

$inbox is define as a static array in core.php


回答1:


Static data is only static within the context of a class, meaning a static data member in a class is shared by all instances of that class.

What you seem to be talking about is data persisting across multiple HTTP requests. Static data won't do that for you. That's what $_SESSION data is for.

To put it another way: once a script finishes servicing the current request, it completely dies. All data is had is completely cleaned up. The new request starts fresh.

Session data persists until PHP decides to clean it up or you manually destroy it. Typically all you have to do to use session data is put in your script:

Script 1: mailbox.php

session_start();
$_SESSION['mailbox'] = array( /* messages */ );

Script 2: showmail.php

session_start();
$mailbox = $_SESSION['mailbox'];

One thing to note: if your script is long-running try and put a session_commit() in as soon as possible because session access blocks in PHP, meaning if another script tries to session_start() for the same user it will block until the first script finishes executing or releases the session.




回答2:


php Sessions needs a place to store session data between requests. In your case it is a temp\php\session\ folder in your home directory. Either create that folder or change session.save_path in php.ini to point to a valid directory.




回答3:


If your core file provides the right data to mailbox.php, but not showmail.php it's related to something you are (or are not) doing in showmail.php.



来源:https://stackoverflow.com/questions/601307/php-static-variables-across-multiple-php-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!