PHP Variables

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,

<?php
$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,

<?php
$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.
Photo of Vincy, PHP developer
Written by Vincy Last updated: July 2, 2022
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Continue Learning

These related tutorials may help you continue learning.

Leave a Reply

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

Explore topics
Need PHP help?