I'm still fairly new to PHP and so I'm attempting to understand scope concepts within PHP web applications.
In the Java world a Java web app - using Java Server Pages (JSP) and upward - will allow a Java Bean to have the following levels of scope:
- Page
- Request
- Session
- Application
Attempting to map these to PHP's scoping capabilities:
- Page: not really but objects that are local to a call are considered 'gone' after the function call is made so it's sort of like a page scope
- Request: made by using the "$_REQUEST super global (not sure where this goes ... Cookies? Hidden fields? URL parameters?)
- Session: using PHP's $_SESSION super global (where some of the documentation and forum feedback states that this is not a great place to put sensitive information for security reasons)
- Application: using PHP's APC (a Stack Overflow link)
Am I totally out to lunch or are these reasonably similar? I know that one major difference is PHP's ["Shared Nothing"][5] architecture as compared to Java's which is to allow for sharing.
Any advice/guidance/sobering corrections most welcome.
You're on the right track. PHP is indeed Share-Nothing.
In a web context, a php application runs, in it's entirety, once for each HTTP request. This means for every HTTP request the interpreter reads, parses and executes the script (this is simplified - using an opcode cache like APC removes the reading/parsing overhead).
PHP feeds input to the script in the form of superglobals, such as $_REQUEST and $_SESSION. Superglobals are different from regular global variables in that they're automatically available in every scope, so there's no need to use the global
keyword.
Any data that persist between requests need to be stored externally. To share data across requests to maintain state for a user, you typically use $_SESSION, which by default is serialized and written to files on disk (but can be configured to use a memory cache or database). Data that are to be shared between sessions (which I suppose is similar to the Application scope in the JSP world) need to be stashed somewhere external. You can use a memory cache like APC or memcache, or write flat files to disk, or stick stuff in a database, or use any other scheme you can come up with. At the end of the day, there's nothing built-in.
Aside from superglobals, variable scope is fairly boring. By default, variables live in the scope in which they're created.
To reference a global variable in a non-global scope (ie: inside a function), you need to import the symbol into the local scope using the global
keyword. PHP works this way to make it harder to accidentally clobber global variables.
This stuff, and more, is covered pretty well in the manual.
You should probably look at this:
http://php.net/manual/en/language.variables.scope.php
You've got local and global scope, superglobals, static variables. And that page explains how those each work.