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

Latest Article

Blog

PHP Magic Methods

__get()/__set() – These are magic getters and setters for getting and putting values for class properties created dynamically. __isset() – This magic method will be invoked automatically while checking whether a required overloaded property is Read more…

Blog

WordPress Upgrade

The WordPress upgrade released time to time. We provide a WordPress upgrade, content management and maintenance services at affordable price. WordPress upgrade fixes bugs, runs cleaner, faster, and is more secure and stable. We will Read more…

Blog

Magento 2 Upload image in product

If you are trying to upload image on respective product by script then below code will help you to solve this issue. by this code you can set product thumbnail, small and large image. $objectManager Read more…