PHP Variables

by Vincy. Last modified on July 2nd, 2022.

A 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 a string variable whereas $count is int, based on the value.

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 a 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 a separate file, class or function we have to use the global keywords. 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 local variables.
  • Superglobals – These are predefined global variables. For example, $_GET, $_SERVER and etc. It can be accessed from anywhere without the global keyword.
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page