PHP Variables

What is Variable in PHP

PHP variables are used to store data such as text, digit, etc. The value of a variable can be stored using = an assignment operator. there is no need to define data type like C programming language such as int, float, char, PHP converts the variable automatically to the appropriate form of data, based on its value.

How to define the PHP variables

In PHP variables are declared using $ symbols and then after the name of the variable and as per PHP syntax every statement ends with a semi-colon ; . for example $variable_name; assign value to a variable using = assignment operator. for example $variable_name="webgator";

php variable

In the above example $name variable store text values and the $number variable stores the numeric value. there is no need to declare datatype for PHP variables it automatically converts variables data type as per the values of the variables. we use the echo statements to display the value of variables. echo statement use in PHP to display the values. we will discuss more the echo statement in some other post.

Naming Conventions for PHP Variables

  • The naming conventions for PHP Variables are as follows.
  • Variable must start with the alphabet or underscore ( a-z, A-Z, _ ).
  • Start variable with digit not allow.
  • Built-in keywords are not allowed.
  • Variables declared using $ sign followed by the variable name.
  • Only alphabet underscores and digits are allowed.
  • Whitespace and special character ( except underscore _ ) not allow.

Variables Scope

In PHP you can declare variables anywhere in the script.

PHP has three different variable scopes:

  • Local
  • Global
  • Static

Local :
A variable declared as part of a function has a LOCAL SCOPE and can be accessed only as part of it. it means the variable which is declared inside of any function can not be accessed outside of the function. In different functions, you can have local variables of the same name, since local variables are known only by the function in which they are defined.

Global :
A variable declared outside a function has a GLOBAL SCOPE and is available only outside a function. it means we can not access that variable inside any functions which are globally declared.

Static :
Normally all of its variables are removed when a task is completed/executed. We do, however, often want to NOT delete a local variable. We need that for an additional task. Then that variable would still have the information it holds from the last time the function was called, each time the function is called.