Variables in PHP

Posted By: Jas Singh

This is the second post of a series of PHP Introduction posts. Be sure to check out the first post, An Introduction to PHP and check back for additional posts in the future to learn all about PHP!

Variable Declaration

A variable always begins with a dollar sign, $, which is then followed by the variable name. eg: $color Variables do not have to be explicitly declared in PHP. Rather, variables can be declared and assigned values simultaneously.

Value Assignment

Assignment by value simply involves copying the value of the assigned expression to the variable assignee. This is the most common type of assignment. A few examples follow:

$color = "red";
$number = 12;

Reference Assignment

Reference Assignment means that you can create a variable that refers to the same content as another variable does. Therefore, a change to any variable referencing a particular item of variable content will be reflected among all other variables referencing that same content. You can assign variables by reference by appending an ampersand (&) to the equal sign. Let’s consider an example:

<?php
    $value1 = "Hello";
    $value2 = &$value1;    // $value1 and $value2 both equal "Hello"
    $value2 = "Goodbye";   // $value1 and $value2 both equal "Goodbye"
?>

Global Variables

A global variable can be accessed in any part of the program. To modify a global variable, however, it must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. Consider an example:

$somevar = 15;

function addit() {
    GLOBAL $somevar;
    $somevar++;
    echo "Somevar is $somevar";
}
addit();

The displayed value of $somevar would be 16. However, if you were to omit this line,

GLOBAL $somevar;

the variable $somevar would be assigned the value 1 because $somevar would then be considered local within the addit() function. This local declaration would be implicitly set to 0 and then incremented by 1 to display the value 1.

An alternative method for declaring a variable to be global is to use PHP’s $GLOBALS array. Reconsidering the preceding example, you can use this array to declare the variable $somevar to be global:

$somevar = 15;

function addit() {
    $GLOBALS["somevar"]++;
}

addit();
echo "Somevar is ".$GLOBALS["somevar"];

This would print: Somevar is 16

Static Variables

The final type of variable scoping to discuss is known as static. A static variable does not lose its value when the function exits and will still hold that value if the function is called again.

function keep_track() {
    STATIC $count = 0;
    $count++;
    echo $count;
    echo "
"; } keep_track(); keep_track(); keep_track(); 1 2 3

PHP’s Superglobal Variables

PHP offers a number of useful predefined variables that are accessible from anywhere within the executing script and provide you with a substantial amount of environment-specific information.

$_SERVER: Stores information about server and current script.

  • $_SERVER[‘HTTP_REFERER’]: The URL of the page that referred the user to the current location.
  • $_SERVER[‘REMOTE_ADDR’]: The client’s IP address.
  • $_SERVER[‘REQUEST_URI’]: The path component of the URL. For example, if the URL is http://www.example.com/blog/apache/index.html the U,RI is /blog/apache/index.html.
  • $_SERVER[‘HTTP_USER_AGENT’]: The client’s user agent, which typically offers information about both the operating system and the browser.

Retrieving Variables Passed Using GET

The $_GET superglobal contains information pertinent to any parameters passed using the GET method. If the URL http://www.example.com/index.html?cat=apache&id=157 is requested, you could access the following variables by using the $_GET superglobal:

$_GET['cat'] = "apache"
$_GET['id'] = "157"

Retrieving Variables Passed Using POST

The $_POST superglobal contains information pertinent to any parameters passed using the POST method. Consider the following form

<form action="subscribe.php" method="post">
   <p>
      Email address:<br />   
   <input type="text" name="email" size="20" maxlength="50" value="" />
   </p>
   <p>
      Password:<br />
      <input type="password" name="pswd" size="20" maxlength="15" value="" />
   </p>
   <p>
      <input type="submit" name="subscribe" value="subscribe!" />
   </p>
</form>

The following POST variables will be made available via the target subscribe.php script:

$_POST['email'] = "jas@fellowshiptech.com";
$_POST['pswd'] = "jsingh";
$_POST['subscribe'] = "subscribe!";

Retrieving Information Stored Within Cookies

The $_COOKIE superglobal stores information passed into the script through HTTP cookies. Such cookies are typically set by a previously executed PHP script through the PHP function setcookie().

Retrieving Information About Files Uploaded Using POST

The $_FILES superglobal contains information regarding data uploaded to the server via the POST method. This superglobal is different from the others in that it is a two-dimensional array containing five elements. The first subscript refers to the name of the form’s file-upload form element; the second is one of five predefined subscripts that describe a particular attribute of the uploaded file:

  • $_FILES[‘upload-name’][‘name’]: The name of the file as uploaded from the client to the server.
  • $_FILES[‘upload-name’][‘type’]: The MIME type of the uploaded file. Whether this variable is assigned depends on the browser capabilities.
  • $_FILES[‘upload-name’][‘size’]: The byte size of the uploaded file.
  • $_FILES[‘upload-name’][‘tmp_name’]: Once uploaded, the file will be assigned a temporary name before it is moved to its final location.
  • $_FILES[‘upload-name’][‘error’]: An upload status code.

Retrieving Information Stored in Sessions

The $_SESSION superglobal contains information regarding all session variables. Registering session information allows you the convenience of referring to it throughout your entire Web site, without the hassle of explicitly passing the data via GET or POST When a session variable is declared, it remains in memory until it is explicitly unset,  session times out, or the browser is closed. You must initiate session data before you can use session variables by calling session_start() at the top of your script. You can destroy a session variable by using unset()

Unset($_Session['username']);

Session_destroy() destroys the current session the next time the page loads. However, the session variable remains available with the same script.

Session_start();
$_SESSION['test'] = "Hi";
Session_destroy();
Echo $_Session['test']; //'test' is still available
Unset ($_Session['test']);
Echo $_Session['test']; // Error

Jas Singh is a Technical Lead for Fellowship Technologies. He has been with Fellowship Technologies since July 2007. He believes that every new day brings opportunities to learn something new.

 

Posted In: API, Tips,

Comments:
No one has commented yet. Be the first!
Commenting is not available in this channel entry.

Categories:

Previous Posts:


Subscribe to the RSS feed!