Developer Guide

Usage of Variable & its Scope in PHP

In the last tutorial, I guided you through the Installation Procedure of XAMPP, Now we will discuss variables and their scope. But before that, if you have not seen the previous posts Introduction to PHP & How to install PHP.

What is a Variable?

In mathematical terminology, a variable is an entity that can vary or have different values in a different state. In contrast to a variable in the mathematical world, a variable is an entity that could change and store some identifiers and constants. So it is more like a container.

Creating / Declaring PHP Variables:

If you are from a C or Java background. Whenever you want to use a variable you need to declare it first then only you can use it to store value, but, Since PHP is an interpreted language, so like other interpreted languages, the Variable doesn’t need to be declared first. Doesn’t it make sense to call a variable a container, as in the real world, a container can store anything capable of being fit inside it, similarly a PHP variable can store anything. A variable in PHP starts with the $ symbol. For Example:

<?php
$name=”Tekraze “;
$Roll_no=27;
$fees=500.80;
echo “These are my Variable: “;
echo $name, $Roll_no,” “, $fees;
?>

OUTPUT: These are my Variable: Tekraze, 27, 500.80

As shown in the above snippet, the three variable created above $name, $Roll_no, $fees will hold the value Tekraze, 27, and 500.80 correspondingly.

To output the text we have seen that we printed a string “These are my Variable” with one echo command and variable in another command. But Sometimes you need to interpolate the variable in the long string then how you will do it, it can be performed in two ways as shown below:

<?php
$blogger_name=”Rahul Chanana”;
$blog=”Tekraze”;
$posts=5;
echo “This is $blogger_name from $blog, and this is my $posts th posts”;
?>

<?php
$blogger_name=”Rahul Chanana”;
$blog=”Tekraze”;
$posts=5;
echo ‘This is ‘.$blogger_name.’ from ‘. $blog.’, and this is my’.$posts.’ th posts’;
?>

Output:This is Rahul Chanana from Tekraze, and this is my 5 th post

Things Learned

  • A Text (called as the string in programming languages) can be created by enclosing symbols in ” ” or ‘ ‘.
  • If You want to print value of a variable then you can create it in two ways, by enclosing the variable in double quote as in snippet 2 or concatenation with string using dot operator as shown in snippet 3
  • Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it. Therefore PHP is a loosely Typed Language (doesn’t require any variable declaration before using it)

Rules for PHP variables:

  • A variable can have a short name (like x and y) or a more descriptive name (age, carName, total_volume).
  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)

Variable Scope:

In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

So there are basically three variable scopes in PHP, which are:

  1. Local – Any variable declared within a function.
  2. Static – Any local variable that can live out of its scope. Similar to local variables, static variable too can only be used within a function.
  3. Global – Any variable that can be accessed from anywhere.

Let’s check out the below PHP code first and later we can go with further explanation on the variable scopes.

$y = 5; // global variable
    testAll();
    testGlobalAndStatic(); // Call 1
    testGlobalAndStatic(); // Call 2
    function testAll() {
        $x = 8; // local variable
        global $y; // accessing a global variable
        static $z = 10; // static variable
        echo "<p><strong>testAll function</strong>: Variable x is a local variable and it's value is: $x</p>"; //8
        echo "<p><strong>testAll function</strong>: y is a global variable and it's value is: $y</p>"; // 5
        echo "<p><strong>testAll function</strong>: z is a static variable and it's value is: $z</p>"; // 10
        $z++;
        static $z = 10; // this statement never applies, as $z has already been declared as static
        echo "<p><strong>testAll function</strong>: The value of static variable z now is: $z</p>"; // 11
        $z = 10;
        echo "<p><strong>testAll function</strong>: The value of static variable z now is: $z</p><br>"; // 10
        $y = $y + 1; // can also be written as $y++
    }<span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1">​</span><span class="crayon-h"></span>
 function testGlobalAndStatic() {
        $a = 99;
        static $b = 99;
        global $y; // accessing a global variable
        echo "<p><strong>testGlobalAndStatic function</strong>: y is a global variable and it's value is: $y</p>";// First call - 6, Second call - 6
        echo "<p><strong>testGlobalAndStatic function</strong>: a is a local variable and it's current value is: $a</p>"; // First call - 99, Second call - 99
        echo "<p><strong>testGlobalAndStatic function</strong>: b is a static variable and it's current value is: $b</p>";// First call - 99, Second call - 100
        // Now incrementing both local variable a and static variable b
        $a++;
        $b++;
        echo "<p><strong>testGlobalAndStatic function</strong>: The value of local variable a after incrementing by 1 is: $a</p>";// First call - 100, Second call - 100
        echo "<p><strong>testGlobalAndStatic function</strong>: The value of static variable b after incrementing by 1 is: $b</p><br>";// First call - 100, Second call - 101
    }<span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1">​</span>

Try to understand each and every line of the PHP code and its output above.

Below are few important points to note:

  • A local variable scope is only within a function, which means they can be declared and accessed within the same function. Therefore as soon as the function execution ends, all its local variables get destroyed and are no more accessible.
  • Static variables are similar to local variables, except that static variables hold the values even after the function execution gets completed, which means they are not destroyed after the function execution completes. This can be clearly understood from the above code snippet, where we are calling the testGlobal And Static function twice one after the other.

So this is for today, in our next tutorial we will learn about Data Types in PHP. Stay connected with us for more tutorials.

If you like this tutorial please share it with your friends, colleagues and with your relatives, keep visiting and be a part of the Tekraze family. If you have any problem with this tutorial please comment in the comment box and if you have any suggestion regarding this then please tell us.

This post was last modified on March 3, 2024 3:11 am

RAHUL CHANANA

UX /UI designer who loves clean, simple & unique design. i also enjoy crafting brand identities, icons, & ilustration work. An Graduate Student of Information Technology, Guru Jambheshwar University of Science & Technology, Hisar. Love to discover new things about tech and loves to design. Expertise in Graphic Designing with photoshop CS6 and CC. Also a little bit command over GIMP and CorelDRAW. I also have a knowledge of C, C++, Core Java, HTML5, CSS3, Bootstrap4, JavaScript and PHP. In free time i love to play cricket ,watch web series and love to travel.

Leave a Comment

View Comments

  • Thanks for sharing the informative blog post. I have found here lots of interesting information for my knowledge I need. All the details you provide to us, it was very helpful and useful. Thanks for sharing this amazing post. I appreciate your efforts.
    Check out some latest Shopping Apps

Recent Posts

Tailoring Web Design For Niche Markets

In today's digital landscape, distinguishing your brand in a niche market requires more than just…

2 days ago

Frecciarossa high-speed trains at the forefront in sustainability and innovation

Trenitalia, the lead company of the FS Group’s Passenger Division, is taking concrete steps every day…

2 days ago

AI HACKING OF MARCH MADNESS BETTING TO COST U.S. COMPANIES RECORD AMOUNTS IN 2024

CLEVELAND, OH – March 12, 2024 – Advizex, a leading technology provider of infrastructure and…

2 days ago

How AI-Based Paraphrasing Tools Help You in Writing Blog Content

Unique, entertaining content is essential for attracting readers and increasing website traffic. Writing original content…

2 days ago

How To Maintain Your Outdoor Security Equipment

Ensuring the effectiveness of your outdoor security system involves more than just installation—maintenance plays a…

1 week ago

Beneath the Surface: GIS and the New Age of Bathymetric Exploration

Exploring the depths of our oceans has always been challenging, but with Geographic Information Systems…

1 week ago