Creating (Declaring) PHP Variables

All variables in PHP start with a $ (dollar) sign followed by the name of the variable.A valid variable name starts with a letter (A-Z, a-z) or underscore (_), followed by any number of letters, numbers, or underscores.

If a variable name is more than one word, it can be separated with an underscore (for example $employee_code instead of $employeecode).'$' is a special variable that can not be assigned.

Example -

PHP Variables

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

PHP variables Rules:

  • 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)
  • PHP is a loosely type language

    In a language such as C, C++, and Java the programmer must declare the name and type of the variable before use it. In PHP the type of the variable does not need to be declared before use it because types are associated with values rather than variables. As a result, a variable can change the type of its value as much as we want.

    As previously mentioned you don't need to declare variables or their type before using them in PHP. In the following example, none of the variables are declared before they are used, the fact is $height is floating number and $width is an integer.

    Example -

    PHP Variables 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.

    PHP three different variable scopes:

  • local
  • global
  • static
  • The global keyword

    We have already learned variables declared outside a function are global. They can be accessed anywhere in the program except within a function.

    To use these variables inside a function the variables must be declared global in that function. To do this we use the global keyword before the variables.

    Example -

    PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.

    Example -