PHP variables

php variables

Variables

PHP variables are used for storing a values, like text strings, numbers or arrays. When a variable is set it can be used over and over again. Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

The correct way of setting a variable in PHP:
$var_name = value;

Predefined variables
PHP provides a large number of predefined variables to any script which it runs.

PHP Superglobals

$GLOBALS
Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.

$_SERVER
Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).

$_GET
Variables provided to the script via URL query string. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).

$_POST
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).

$_COOKIE
Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).

$_FILES
Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.

$_ENV
Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).

$_REQUEST
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted.

$_SESSION
Variables which are currently registered to a script’s session.

Variable scope
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.

For example

<?php
$a = 1;
include 'b.inc';
?>

Here the $a variable will be available within the included b.inc script. However, within user-defined functions, a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.

Variable Naming Rules
A variable name must start with a letter or an underscore “_”
A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ )
A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)

You may also like...