PHP Variable


PHP Variable

Variables are like a container used to store information to be referenced and manipulated in a computer program.

  • Variables in PHP are pieces of data identified by a name and have the ability to store data of many types.
  • Variables in PHP are represented by a dollar sign ($) followed by the name of the variable.
  • The variable name is case-sensitive, meaning a variable named $name is different from $Name. These two variables with different character cases can each contain a unique value.
  • Variable names follow the same rules as other labels in PHP.
  • A valid variable name starts with a letter or underscores, followed by any number of letters, numbers, or underscores.
  • PHP has a total of ten data types which we use to construct our variables.
  • By default, variables are always assigned by value. That means when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that changing one variable's value will not affect the other after assigning one variable's value to another.

<?php

$Var = 'Hello';

$var = 'World';

echo "$var, $var";      // outputs "Hello, World"

 

$1one = 'not sure';     // invalid; starts with a number

$_1one = 'not sure';    // valid; starts with an underscore

$säy = 'Hello World!!';    // valid; 'ä' is (Extended) ASCII 228.

?>

 

PHP also offers another way to assign values to variables assigned by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

<?php

$name = 'Yunus';              // Assign the value 'Yunus' to $name

$References = &$name;              // Reference $name via $References.

$bar = "My name is $References";  // Alter $References...

echo $References;

echo $name;                 // $name is altered too.

?>

 

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - Boolean default to false, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become an empty array.

Predefined Variables

  • PHP provides a large number of predefined variables to any script which it runs. However, many of these variables cannot be fully documented as they depend upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line.
  • PHP also provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input.
  • These arrays are rather special in that they are automatically global - i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals). Superglobals cannot be used as variable variables inside functions or class methods.

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. For example:

<?php

$a = 1; /* global scope */

 

function test()

{

    echo $a; /* reference to local scope variable */

}

 

test();

?>

 

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. In PHP global variables must be declared global inside a function if they are going to be used in that function. In general, PHP has three different variable scopes: Global,and static

Global Variable

  • PHP variables that are not declared inside any function and can be used by any function are called Global variables.
  • The advantage of global variables is that any function can use its value to do any kind of operation. It helps in saving time and memory by not creating variables again and again for the same value. But to use these variables inside a function we have to use a global or $GLOBALS array. Using a global keyword outside a function is not an error. It can be used if the file is included from inside a function. Let us see these examples

<?php

$a = 1;

$b = 2;

 

function Sum()

{

    global $a, $b;

 

    $b = $a + $b;

}

 

Sum();

echo $b;

?>

 

The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. Let us see if the previous example can be rewritten as:

<?php

$a = 1;

$b = 2;

 

function Sum()

{

    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];

}

 

Sum();

echo $b;

?>

 

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element.

Static Variable

  • Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
  • Static variables in PHP are declared using the 'static' keyword. After declaring any PHP variable 'static', it will not get deleted from the memory till the program is getting executed.
  • PHP continuously erases the variables of a function from the memory after the effective execution of the function. But what in case we require any variable's value indeed after the execution of a function, like we may have to increment or decrement the value different times. So, what we will do to stop PHP from erasing variables from the memory? we utilize the static variables.

 

<?php

function test()

{

    static $a = 0;

    echo $a;

    $a++;

}

?>

 

Now, $a is initialized only in the first call of the function, and every time the test() function is called it will print the value of $a and increment it.

Static variables also provide one way to deal with recursive functions. A recursive function calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

<?php

function test()

{

    static $count = 0;

 

    $count++;

    echo $count;

    if ($count < 10) {

        test();

    }

    $count--;

}

?>

 

Static variables can be assigned values that are the result of constant expressions, but dynamic expressions, such as function calls, will cause a parse error. Static declarations are resolved in compile-time.

References with global and static variables

PHP implements the static and global modifier for variables in terms of references.

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on.

 Superglobals

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods. These superglobal variables are:

  • $GLOBALS
  • $_SERVER
  • $_GET
  • $_POST
  • $_FILE
  • $_COOKIE
  • $_SESSION
  • $_REQUEST
  • $_ENV

By default, all of the superglobals are available but there are directives that affect this availability. For further information, refer to the documentation for variables_order.

Superglobals cannot be used as available variables inside functions or class methods.

 

 


Leave a comment
No Cmomments yet