PHP Variables

PHP variables are like containers used to store values and expressions.

PHP variables are prefixed by a dollar sign $ followed by the variable name.

PHP variable names are case-sensitive.

<?php
     //The variable "store" holds the value "Hello"
     $store = "Hello";

     echo $store; // prints "Hello"
?>

PHP Variable Scope

A variable scope is a context where a variable can be accessed or used.

The scope of a variable can be:

  • Global
  • Local
  • Static

PHP Global Variables

A global variable is generally accessible anywhere in the code, thus the words global. Basically, a global variable should be defined outside of the scope or block that needs it.

Do It Yourself

  Do It Yourself

PHP Global Keyword

The global keyword lets you access a global variable inside a function. It makes a variable that is outside a function accessible in the function.

Example

  Do It Yourself

Global variables can also be stored as arrays in PHP by using the $GLOBALS[index] where the index is the name of the variable.

Example

  Do It Yourself

Here is another example that explains how variables are accessed in PHP

Example

  Do It Yourself

What You Should Know at the End of This Lesson

  • You should be able to declare PHP variables.
  • You should about PHP variable scopes.
  • You should know about the global keyword.