In PHP, a variable can have a short name or a variable begins with the $ sign, chased by the name of the variable.
Laws for variables:-

  • A variable begins with the $ sign, chased by the name of the variable
  • A variable name must begin with a letter or the underscore character
  • A variable name could only hold alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive

Example:-
<?php
$txt = “Hello India!”;
$x =1 5;
$y = 101.5;
?>

OR

<?php
$txt = “India”;
echo “I love $txt!”;
?>

OR

<?php
$txt = “World”;
echo “I love ” . $txt . “!”;
?>

OR

<?php
$x = 15;
$y = 14;
echo $x + $y;
?>
Variables Scope:-
In PHP, variables can be declared anywhere in the script and it could be reused.

PHP has three different variable scopes:-

  • local
  • global
  • static

Global and Local Scope:-
A variable stated outside a function has a GLOBAL SCOPE and could be accessed outside a function:-
Example:-
<?php
$x = 15; // global scope

function gfirst() {
echo “<p>Variable value: $x</p>”;
}
gfirst ();

echo “<p>Variable value: $x</p>”;
?>
Global Keyword:-
This is used to contact a global variable from within a function.
Example:-
<?php
$x = 5;
$y = 10;

function gfirst() {
global $x, $y;
$y = $x + $y;
}

gfirst();
echo $y; // outputs 15
?>
Static Keyword:-
Typically, when a capacity is executed, the greater part of its variables are erased. In any case, once in a while we need a nearby variable NOT to be erased. To do this, utilization the static watchword when you first announce the variable:-
Example:-
<?php
function gfirst() {
static $x = 0;
echo $x;
$x++;
}

gfirst();
?>

Categories: PHP

0 thoughts on “PHP Variables”

Leave a Reply