Introduction
In my previous blog, I talked about a basic introduction to PHP.
In this blog, we will discuss "PHP VARIABLES".
PHP Variables
What is Variable?
- Variables are used to store the value and access the stored value in the program.
In PHP, variables begin with the "$" symbol, followed by the Variable name.
Example:
Rules for assigning a Variables:
Basically, a Variable can have a short name (like i,e., x,y,etc..) or larger names (like i,e., first,age_group,etc..),
- A Variable name must start with underscore characters or with a letter.
- A Variable name cannot begin with numbers.
- A variable name can contain only alpha-numeric characters and underscores ( A-Z, 0-9 and _ ).
- Variable names are case-senstive($NAME, $name), these names are two different variable names.
PHP OUTPUT VARIABLES
- The "echo" statement is often used to show the output to the screen.
Example 1
- <?php
- $m = "BEST WISHES!";
- echo"$m";
- ?>
Example 2
- <?php
- $a = 2;
- $b = 1;
- echo $a + $b ;
- ?>
PHP VARIABLES SCOPE
- Variables are declared anywhere in the program script.
- A PHP consist of three types of variable scopes:
- Global
- Local
- Static
Global Variable
- A variable declared outside of the function is known as a global variable.
- It can be accessed outside of the function and anywhere in the program.
Example 1
- <?php
- $x = 2;
- function test()
- {
- echo"<p>WELCOME: $x</p>";
- }
- test();
- echo"<p>WELCOME : $x</p>"
- ?>
- The global variables are accessed from inside of the function with the help of the keyword "global".
- Use the "global" keyword before the declared function variable (inside).
Example 2
- <?php
- $a = 2;
- $b = 2;
- function test()
- {
- global $a, $b;
- $b = $a * $b;
- }
- test();
- echo $b ;
- ?>
Local Variable
- A variable declared inside of the function is known as local variable.
- It can be accessed only inside that function.
- The local variables can have the same names with different functions because they can be recognized only by their declared function names.
Example:
- <?php
- function test()
- {
- $x = 2;
- echo"<p>WELCOME: $x</p>";
- }
- test();
- echo"<p>WELCOME FUNCTION IS : $x</p>";
- ?>
Static Variable
- Generally,when the function gets executed,all the variables in the function are deleted.
- Sometimes, we want some of the local variables for further references.
- For that purpose, use the "static" keyword before the variable in the function declaration.
Example
- <?php
- function test2()
- {
- static $a = 1;
- echo"$a";
- }
- test2();
- ?>
These are all the PHP Variables.
Here, I have attached the example codings for the above-discussed topics. Kindly refer to it.
Thank you!.