Learn PHP Variable

Learn PHP Variable Tutorial. Variable is used to save data like number, string, date & time etc.. PHP variable starts with the $ sign followed by the name of the variable. i.e $x, $y, $z A PHP variable name must start with a letter or the underscore character. A PHP variable name cannot start with a number. A PHP variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) PHP Variable names are case-sensitive. The PHP echo statement is used to display output data to web browsers . PHP is a Loosely Typed Language because we don’t need to define data type for variable. PHP automatically declare a data type to the variable by depending on its value.

Syntax of declaring a variable in PHP is given below:
$variable_name="Value";

PHP Example :

<?php
        $var = "Learn php variable!";
        echo $var;

?>
Output:
Learn php variable!


PHP has three different variable scopes
1. Local scope : A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function
2. Global scope : A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function
3. Static scope : static variable inside function will not delete its value when function exists.
4. Function parameters : it can by passed through function name.

According to scope , There are four types of variable.
1. Global Variable : Global Variable is used to access value within function. It can be defined by GLOBAL Keyword.
2. Local Variable: A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function
3. Static Variable : Static Variable can be defined by STATIC keyword. static variable will not lose its value when the function exits and will still hold that value when the function will be called again.
4. Function Parameters: Function parameters are declared after the function name and inside parentheses.

Rules for declaring PHP variable:

  1. A variable must start with a dollar ($) sign followed by the variable name.
  2. PHP variable name can only contain alpha-numeric character and underscore (A-z, 0-9, _).
  3. PHP variable name should not contain spaces.
  4. A variable name must start with a letter or underscore (_) character.
  5. PHP variables are case-sensitive, so $varname and $VARNAME both are different variable.
  6. PHP variable name should not start with a number or special symbols.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

80255