PHP Variables



A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form:
$variable_name = Value;

If you forget that dollar sign at the beginning, it will not work.

Note: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable. The variables $a_number and $A_number are different variables in PHP
There are a few rules that you need to follow when choosing a name for your PHP variables.

Ø  PHP variables must start with a letter or underscore "_".
Ø  PHP variables may only be comprised of alpha-numeric charactehrs and underscores. a-z, A-Z, 0-9, or _ .
Ø  Variables with more than one word should be separated with underscores. $my_variable
Ø Variables with more than one word can also be distinguished with capitalization. $myVariable

Scope of Variables

 1.      Local Variables
2.      Global Variables
3.      Static Variables




1.      Local Variables

A variable declared within a PHP function is local and can only be accessed within that function.

2.      Global Variables

A variable that is defined outside of any function has a global scope.
Global variables can be accessed from any part of the script, EXCEPT from within a function.

3.      Static Variables

When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be deleted.
To do this, use the static keyword when you first declare the variable:


Local Example
Global Example
Static Example
<?php
$x=5; // global scope function myTest()
{
echo $x; // local scope
}
myTest();
?>
<? php
$x=5; // global scope
$y=10; // global scope function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
<?php
function myTest()
{
static $x=0; echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>


No comments:

Post a Comment

=>Advanced Java Programming (J2EE)

1.  Syllabus 2. Unit Wise Question/Material 3. Paper 4. Previous Paper