PHP Global Variable
- Are they available application wide e.g: if they are created on index.php are they values available in file.php
- Is the value of the global variable same for each user. Say I have one user doing something and his global variable value is 1. Will the second user who visits the same page his value also be 1? edited:
- Taking the advice from here: I have decided to use value by reference
- Result I need to achieve is:
- New session should have the same results and $name variable in any other file not included should not be associated with this variable.
name: initial vj name: vj name: vj name in file2: vj
Code:
<?php $name ; $name ='initial vj'; echo '<br/>name: ' .$name; test($name); function test(&$name) { $name = 'vj'; echo '<br/>name: ' .$name; } echo '<br/>name: ' .$name; include('file2.php'); ?>
<?php $name; echo '<br />name in file2: ' .$name; ?>
Advertisement
Answer
This concept is called “application scope.” PHP is better equipped for a scope of session, request or page. To place data within application scope in PHP, it’s more common to make a database call to get the value.
We can use superglobals like $_SESSION, $_REQUEST or $_POST and $_GET to assign the variable to live beyond just one page, inside the session, request or page scopes. PHP doesn’t have a common, similar method for assigning a value to a variable in application scope. Instead, application scopes are often imitated by calling an outside source of data, like a database or file. Earlier versions of PHP had some features that leaned toward the concept of application scope, but they have been deprecated.
For your questions:
- The question shows the idea of an application scope variable. For example, if you wanted every user to enter a value on index.php and write it to database, then it would be possible to make a call during the creation of file.php that would retrieve that value.
Instead of doing this for all users by one user, we often write this kind of code as a $_SESSION variable, usable by one user at a time. It is common for us to use a database write and a database read to solve this kind of problem. Simply put down the value by the user who writes it. Get it for the readers.
- This is the concept of a static application-scoped variable. To achieve this, simply have both users make similar database calls to retrieve the same value.
There is a super-global named $GLOBALS, but it is more of a shortcut for annotating how a variable is named. It’s not a feature that will bring application scope to the variable.
JSP allows the use of application scoped variables by simple declaration. ASP allows the use of application scoped variables through application configuration with XML. PHP doesn’t directly use application scope in the context of a variable, object or class.
php man scope php man reserved