So what is a variable?

Variables store data of various types. A variable can be accessed, updated, replaced, or removed an unlimited number of times.

What can a variable store?

The data stored can be of any number of different [http://en.wikipedia.org/wiki/Datatype data types]:

  • Discrete data types, such as
    • Boolean — True, False or NULL.
    • Integers — whole numbers (e.g. 1, 2, 3, -5…).
    • Floats — decimal numbers (e.g. 1.0, 2.5…).
    • Strings — text (‘this is a string’).
  • Meta-variables, such as

How do you assign data to a variable?

In PHP, variables are

  • prefixed with the $ (dollar sign)
  • assigned the data to the right of the = (equals sign).

// String
$variableName = 'some data';

// Integer
$number = 1;

// Float
$total = 5.0;

// Array
$carManufacturers = array('Honda', 'Toyota', 'Ford');

// Object
$car = new Car;

How do you specify a variable’s data type?

Most of the time, you can’t specify a variable’s data type.

Remember, PHP is a loosely and dynamically-typed language: Unlike most languages, a variable’s data type cannot be manually defined. It is all based on context: By default, whatever type of data is being assigned determines the data type of the variable. Just like when you say “lion” we think “big cat”, so when you say 1.5, PHP thinks “float”.

In some rare circumstances, letting PHP decide the data type on its own can produce improper or unexpected results. In these situations, the solution is to utilize manual type casting Advanced Topic.

What is a constant?

Constants are identical to variables in every way except that constants are read-only. Constants can only be set once, at the time the application is written, and cannot be changed by the application itself.

That said, there are two types of constants:

define("APP_VERSION", "1.0.1");

echo "Version: " . APP_VERSION;                  // Output: Version: 1.0.1

  • Class constants are defined inside a class:
class MyShoppingCart
{
    const VERSION = 2;
}

echo "Version: " . MyShoppingCart::VERSION;      // Output: Version: 2