PHP variables

PHP variables

Variables in PHP, like in all languages are used for storing values. All variables in PHP start with a $ sign. They can be used to store numbers, strings or arrays. Once the variable is set, it can be used multiple times.

Variables in PHP are case sensitive and by default are assigned by value. Initializing a variable is not mandatory. PHP also has some predefined variables. Different categories of variables include:

$GLOBAL: References all variables available in global scope

$_GET — HTTP GET variables

$_POST — HTTP POST variables

$_SESSION — Session variables

$_REQUEST — HTTP Request variables

Example:
<?php

   $sample =”Sample text”;

?>

How many ways I can register the variables into session?

Global variables in PHP can be registered using the session_register() function. It accepts different number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays

Example:
Session_register(“smple”);

$_session can also be used for registering variables.

Example:
$_SESSION['count'] = 0;

Short note on variable scope in functions in PHP.

The scope of a variable is determined based on the context in which is defined. i.e. local or global. In PHP global variables must be declared global inside a function if they are going to be used in that function.

Example:
The script below will not produce any result because “x” ‘s scope is outside the function. If the variable is declared as global, it can be used from anywhere in the script.

<?php
$x = 10; //global
Function sample()
{
       Echo $x;
}
Test();
?>

Describe $_ENV and $_SERVER.

1. $_ENV is the array under Superglobal variables. They are he environment variables. These variables are imported into PHP’s global namespace from the environment of PHP parser.

Example:
<?php
       Echo ‘my user name is ‘ .$_ENV[“USER”] ‘!’;
?>

Output:
My user name is sample !

2. $_SERVER is the array under Superglobal variables. They are array containing information about headers, paths and script locations. Web server creates entries of this array.

Example:
<?php
       Echo $_SERVER [‘SERVER_NAME’];
?>

Output:
www.sample.com

What is this variable? Explain its purpose.

In order to specify that you are working with local variables within a function $this variable is used. Inside a function of an object, PHP automatically sets the $this variable contains that object – we need not to do anything to have access to it.

Example:
Function person()
{
       Print “{$this->age}”;
}
PHP comment
Single line - Ways to comments, Multiple lines – Ways to comment
PHP conditional statement
PHP – if: If the expression is evaluated to true, the condition.
PHP case switching
PHP – Switch case: Switch case can be considered to be like multiple if else statements.
Post your comment
Discussion Board
xplain in detail
Not able to understnd this variable n $_ENV
monika 07-3-2015