PHP Variables

PHP Variables

A variable is a named memory location which is used to store programs input data and its computational results during execution.The value of variable may change during the execution.

Variables are created in RAM , which is temporary memory that’s why the stored data in variables is also temporary. The data stored in the variable is automatically removed when a program ends.

*A quantity whose value can be changed during
program execution is called Variable.*

In php ,Like all other languages variables are used to store values or data.PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.

Rules for PHP variable names

  • The name of the variable is given by the user at the design time.
  • A variable starts with the $ sign.
  • A variable name may include letters , numbers and underscores(_).
  • The first character of variable must be a letter. The variables 7minute, #home, and 2kg are invalid.
  • Variable names are case-sensitive ($marks and $MARKS are two different
    variables).
  • Variables are assigned with the = operator, the variable on the left-hand side and the expression to be evaluated on the right.

Examples

The most simple example about variables in PHP:

<!DOCTYPE html>
<html>
<body>

<h1> PHP Variable </h1>

<?php

$var = “country”;
echo “I love my $var! “;

?>

</body>
</html>

Output

I love my country!

There is another example to declare variables and display the sum of them.

<!DOCTYPE html>
<html>
<body>

<h1> PHP Variables Sum </h1>

<?php

$first = 7;
$second = 21;

echo $first + $second;

?>

</body>
</html>

Output

28

PHP Variables Scope

Variable scope is known as its boundary within  it can be visible or accessed by code.
Depending on the scopes, PHP has three variable scopes:

i) Local Variables
ii) Global Variables
iii)Static Variables

Local Variables:
Variables that are created within the function,and can only be accessed by that function. They are generally temporary variables that are used to store partially processed results prior to the function’s return.

One thought on “PHP Variables

  1. Pingback: PHP Comments - Najam Awan - IT Consultant

Leave a Reply

Your email address will not be published.