Introduction to PHP - Getting to Know PHP Variables

Guest Posts Paolo Nikko Nuñal

Just like any programming languages, PHP has variables in which serves as "containers" for storing information. You can do this by declaring a "$". Variables in PHP starts with a "$" and variables work the same way in other programming languages.

PHP variables function much like algebra, and can hold strings and numbers. However, when declaring variables there are a few rules that you need to follow. Here are the following.

A variable must start with a $ sign.

A variable must start with the letter or underscore character

A variable should not start with a number

A variable must only contain alpha-numeric characters

Code:

<?php
   $name = "John";
   $_getAddress = "United States";
   $myAge = 23;
?>


As you might notice, that in PHP, the variables do not have a data type. PHP automatically converts the variable to the correct data type depending on the type of value it has assigned. Compared to Java,  or C, the programmer must explicitly declare a data type, however in PHP you don't have to worry about anything.

PHP variables can be declared anywhere on the script. And variables have three variable scopes, that are local, global and static. Variables that are declared outside a function are called Global Variables while variables that are declared inside a function are called Local variables.

Global Variables

<?php
   $name = "John";
   $age  = 23;

   function myFunction()
   {
      echo "Im a function";
      echo $name;
      echo $age;
   }
?>


Global variables can be called anywhere. And when we run that script we are able to return the string John and age 23.

Local Variables

<?php
   function myFunction()
   {
      echo "Im a function";

       $name = "John";
       $age  = 23;
   }

   echo $name;
   echo $age;
?>


In the last example, when we print the variable $name and $age, we are returned with a blank. That is because these two variables are declared inside a function and are undefined when called.