Reading and writing global variables across scripts in PHP

前端 未结 9 1853
悲&欢浪女
悲&欢浪女 2020-12-11 21:56

Does PHP have global variables that can be modified by one running script and read by another?

相关标签:
9条回答
  • 2020-12-11 22:09

    You can actually do this using shared memory, or APC (which is using shared memory itself).

    0 讨论(0)
  • 2020-12-11 22:11

    The only one which could be accessed between scripts is the superglobal $_SESSION array. This is because whatever you store in the array is sent to a cookie, which can then be picked up by the next PHP script.

    Global variables simply mean that they can be accessed in the script regardless of the scope; that doesn't mean they can be sent between scripts.

    So either you have to transfer the variables using the $_SESSION array (this stores a cookie on the client computer, so don't sent any sensitive information through that array) or you can either POST or GET between the scripts to send the variables.

    0 讨论(0)
  • 2020-12-11 22:12

    Global variables are bad in most programming. They're especially bad in multithreaded/multiuser systems like webapps. Avoid. If you must use global variables (rather than global constants) put them in a database with transactions guarding updates.

    Since you talk about different scripts though, it sounds like what you really want is a web application framework in a more application oriented language --- something like Django (python) or Rails (ruby). These let you think of your code much more like a cohesive PROGRAM, rather than a lot of loosely connected scripts that process web requests.

    0 讨论(0)
  • 2020-12-11 22:14

    Each request is handled by a php instance of its own. Global variables in php are only accessible from within the same php instance. However you can use something like the memchached module to share data between different instances (which should usually be faster than writing the data to the filesystem).

    0 讨论(0)
  • 2020-12-11 22:17

    Not as such, but you can use cookies or sessions to maintain data for duration of a user's browsing experience, or you can write to a database or file on-disk if the information needs to persist beyond that.

    0 讨论(0)
  • 2020-12-11 22:20

    No, by design PHP is a "share nothing" architecture, which means nothing is shared between processes running at the same time or between requests running one after another. There are ways to share data, but you have to do it explicitly.

    If you just want to share between 2 requests from the same user, sessions or cookies might be the way to go.

    If you want to share between multiple users, you probably want some sort of shared persistence, either short term in a cache (eg. memcached) or more robust like a database.

    Either way, the data is actually being retrieved and reconstructed on each request. It's just handled automatically for you in the case of sessions.

    0 讨论(0)
提交回复
热议问题