PHP

PHP Variables and Constants

php-variable-and-constant

After learning the PHP Keywords In this post, we learn about the PHP Variables and Constants, and also you will learn how to learn to store information in a variable and use constants for storing fixed values in PHP.

PHP Variables and Constants

PHP Variables


Variables are used to store the data, string, text, and numbers. Variable values can change over the course of a script. Here’re some important things to know about variables:

  • In PHP, a variable can not need to be declared before adding a value. PHP automatically converts the variable to the correct data type, depending on its value.
  • After declaring a variable it can be reused throughout the code.
  • The assignment operator (=) used to assign the value to a variable.

Variable comes to the rescue, A variable is name given to memory location which is used to store particular value. These values may be fixed or it can be dynamic.

In PHP variable can be declared as: $var_name = value;

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

PHP Variables and Constants

Naming Conventions for PHP Variables


These are the following rules for naming a PHP variable:

  • It starts with the $ sign, followed by the name of the variable
  • Name must start with a letter or the underscore character
  • Name cannot start with a number
  • It 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)
Remember that PHP variable names are case-sensitive!
# Example:
<?php 
// Declaring variables
 $txt = "Hello World!";
 $number = 10; 
// Displaying variables value
 echo $txt; 
// Output:
 Hello World! 
echo $number; 
// Output: 
10 
?>

In the above example, we have created two variables where the first one has assigned with a string value and the second has assigned a number. Later we’ve displayed the variables values in the browser using the statement. echo The PHP echo statement is often used to output data to the browser. We will learn more about this in the upcoming chapter.

Variable Types


The variables can be declared anywhere in your PHP program. Based on the declaration of your variable scope is decided for each variable. Scope of a variable means the part of program where variable can be accessed.

Based on scope there are three types of variables.

  1. Local variable
  2. Global variable
  3. Static variable

1. Local Variable

A variable which is declared within any function is known as local variable , it has local scope meaning it cannot be accessed outside the function.

#For Example:

<?php
       function localVariable()
      {
          $a = 6;
          echo $a;
      }
      localVariable();
       echo $a;  
   // Output
      6    
?>

Here in this example $a is declared inside function localVariable() so it can not be accessed outside the function body, so if we try to uncomment the code in our program it will not print the value of $a as its accessed outside the block.

2. Global Variable

A variable declared outside any function has global scope so it can be accessed from anywhere in the program.

#For Example:

<?php
       $a = 6; 
      // global variable
       function globalVariable()
       {
         echo $a;
       }
       globalVariable();
       echo $a;  
      // Output
        6           
?>

Here in this example $a is declared outside the function so it has global scope and it can be accessed inside function as well as anywhere outside in the program.

3. Static Variable

The variable declared with keyword static is known as static variable , it has local scope meaning it can not be accessed outside the function , the benefit of static variable is it retains its value between function calls.

#For Example:

<?php
       function staticVariable()
       {
          static $a = 6;
          echo $a;
          $a++;
       }
       staticVariable();
       staticVariable();
       staticVariable();
?>

For this example the value of $a will be initialized only once for all function calls and the value will be retained between function calls so the output will be 10 for first call , 11 for second call and 12 for the third call.

PHP Constants


Constant is a name or an identifier for a fixed value. Constant are like variables except for that one they are defined so they can not be undefined or changed.

PHP Variables and Constants

A constant is an identifier (name) for a simple value. Value not changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Constants are very useful for storing data that doesn’t change while the script is running. Common examples of such data include configuration settings such as database username and password, website’s base URL, company name, etc.

Constants are defined using PHP’s define() function, which accepts two arguments: the name of the constant, and its value. When defined the constant value the we can be accessed at any time just by referring to its name. Here is a simple example:

Create a PHP Constant


To create a constant, use the define() function.

   define(name, value, case-in-sensitive)

Parameters:

  1. name: Specifies the Name of the constant
  2. value: Specifies the Value of the constant
  3. case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
# Example:
<?php 
    define("GREETING", "Welcome to programmingpot.com !"); 
    echo GREETING; 
   // Output
    Welcome to programmingpot.com !
?>

Naming Conventions for PHP Constants


Name of constants must follow the same rules as variable names, which means a valid constant name must starts with a letter or underscore, followed by any number of letters, numbers or underscores with one exception: the $ prefix is not required for constant names.

In this way, we can use the PHP Variables and Constants in our PHP programming. The PHP Variables and Constants are very important for the core PHP programming. So the PHP Variables and Constants is very important.


Tagged :, ,

74 thoughts on “PHP Variables and Constants

  1. Magnificent goods from you, man. I have take note
    your stuff previous to and you’re simply too fantastic.
    I really like what you’ve acquired right here, certainly like what you are stating and the best way during
    which you say it. You’re making it enjoyable and you
    still care for to stay it sensible. I cant wait
    to learn far more from you. This is really a
    tremendous web site.

    1. Thank You so much @kostenlose for your great words. Keep Staying with us and supporting us. I will write the Qualityful and enjoyable post for all.

  2. Greetings, There’s no doubt that your blog could be having web browser compatibility issues.
    Whenever I look at your site in Safari, it looks fine however when opening in I.E., it has some
    overlapping issues. I simply wanted to give you
    a quick heads up! Other than that, wonderful blog!

    1. Thank You @corrugated roofing London for your Great Advice and Feedback. We will fix this Problem as soon as Possible.

  3. you are actually a good webmaster. The web site loading speed is incredible.
    It sort of feels that you are doing any unique trick.
    Furthermore, The contents are masterwork. you’ve performed a fantastic activity in this subject!

    1. Thank You for your good word. Actually, I using my own WordPress theme and not any more plugins on my website, which makes my website loading speed is very fast. And keep staying with us.

  4. It is perfect time to make some plans for the future and it’s time
    to be happy. I’ve read this post and if I could I want to suggest you some interesting things or suggestions.

    Perhaps you could write next articles referring to this article.
    I wish to read more things about it!

    1. Thank You so much @channel helicopter for your great Suggestion. I definitely refer this article link to other articles. Keep staying with us.

  5. I am extremely impressed with your writing abilities
    as neatly as with the structure to your weblog. Is this a paid subject matter or did
    you customize it your self? Either way stay up the excellent quality writing, it is uncommon to peer a great blog like this one these days..

    1. Thank You so much for your positive comment. this is not any paid subject matter I’m just using my own WordPress theme and customize in my own way. And the subject material is all original which I wrote here. Keep staying with us.

  6. I’ve been taking 2 each day, 1 60 minutes prior to lunch and 1 in the late mid-day
    before supper and have actually shed a great deal of weight started taking it I was watching TELEVISION
    as well as I saw just how a medical professional was supporteding this item so I said why not and
    also it functioned!

  7. The substance has actually been discovered via
    comprehensive research which was carried out on pure garcinia cambogia extract to have a far better understanding and also research study of the material that has actually confirmed to have actually opened new frontiers in the area
    of clinical science that can aid people in minimizing
    their weight in a totally natural as well as reliable fashion without undertaking much inconvenience.

  8. Pingback: Google
  9. Definitely believe that which you stated. Your favorite justification seemed to be on the internet the easiest thing to be
    aware of. I say to you, I certainly get irked while people consider worries that they
    just don’t know about. You managed to hit the
    nail upon the top as well as defined out the whole thing without having side-effects , people
    can take a signal. Will probably be back to get more.
    Thanks

  10. Its like you learn my thoughts! You seem to understand
    a lot about this, such as you wrote the e book in it or something.
    I feel that you simply could do with some percent to pressure the
    message house a bit, however instead of that, this is
    great blog. An excellent read. I’ll certainly be back.

  11. Pingback: essayforme
  12. Very nce post. I just stumbled upon your weblog andd wished to say
    that I have truly enjoyed surfing around your
    blog posts. In anny case I will be subscribing to your feed and I hope
    you write agaijn soon!

  13. Pingback: writeaessay
  14. I found your blog site on google and test a number of of your early posts. Continue to keep up the excellent operate. I just extra up your RSS feed to my MSN News Reader. Seeking forward to studying extra from you in a while!?

Leave a Reply

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