PHP Variables

PHP Variables

Variables are "containers" for storing information.

In PHP, a variable starts with the $ sign, followed by the name of the variable.

Creating Variables

Example

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;

echo $txt; echo "\n"; echo $x + $y; ?>

PHP Variables Scope

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

  1. local: A variable declared inside a function has a local scope and can only be accessed within that function.
  2. global: A variable declared outside a function has a global scope and can only be accessed outside a function.
  3. static: When a function is completed, all of its variables are normally deleted. Using the static keyword prevents a local variable from being deleted.

Unlike other languages, PHP does not require you to declare the data type of the variable. PHP automatically associates a data type to the variable, depending on its value. Because the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error!

(Note: In PHP 7+, strict typing was introduced, but loose typing remains the default).