PHP Variables

Last modified on February 25th, 2017 by Vincy.

Variable is an identifier used to store value. It can be changed or removed at any time. The variable name should start with a $ sign. The syntax is,

$variable_name = value;

While declaring a variable we need not specify its data type. In PHP, the data type of its value is taken as the variable type. For example,

$message = "Welcome to PHPPOT";
$count = 5;

In this example code snippet, the $message is string variable whereas $count is int, based on the value.

php_variable

PHP variable naming conventions

We need to follow the following rules while declaring variables in the PHP script.

  • The variable name should be in alphanumerics.
  • Special characters are not allowed except underscore(_).
  • It should not be pre-defined variable. For example, $this.

Types of variables

In PHP there is various type of variables. This categorization is based on the scope of the variable.

  • Global variables – These variables have global scope and visibility to access from anywhere. For accessing them in separate file, class or function we have to use global keyword. For example global $global_variable_name.
  • Local variables – The variables that are defined and used within some specific function or any other program block are called as a local variable.
  • Superglobals – These are predefined global variables. For example, $_GET, $_SERVER and etc. It can be accessed from anywhere without the global keyword.

This PHP code tutorial was published on May 17, 2013.

↑ Back to Top

Share this Article