PHPIntermediate

PHP Variables

PB Pb28 Master Team July 2nd, 2022 Intermediate

📦 Get the complete source code for this tutorial

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

$message = "Welcome to Pb28 Master";

$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.

📦 Download the full project files and try it locally