Variables and Constants

Variables, Variable Variables and Constants

A variable is $ plus a name starting with a letter or underscore, and its name is case-sensitive ($price is not $Price). Assignment creates the variable and copies the value; & makes a reference, a second name for the same value (Functions and Closures).

References, variable variables and constants (variables.php)PHP
<?php
$price = 10;
$copy = $price;              // assignment copies the value
$alias = &$price;            // a reference: a second name for the same value
$price = 12;
$field = 'title';
$$field = 'PHP Basics';      // a variable variable: this creates $title
echo "$price $copy $alias | $title | ", ${'ti' . 'tle'}, "\n";
define('TAX_RATE', 0.08);    // a function call: runs when execution reaches it
define('TAX_RATE', 0.1);     // a constant cannot change
echo $discount;              // an undefined variable warns and reads as null
Output
12 10 12 | PHP Basics | PHP Basics
PHP Warning:  Constant TAX_RATE already defined, this will be an error in PHP 9 in
  /tmp/ch04-02/variables.php on line 10
PHP Warning:  Undefined variable $discount in /tmp/ch04-02/variables.php on line 11

A variable variable takes its name from another variable's value; an array such as $data['title'] does the same job visibly. "${name}" inside a string is deprecated since 8.2 in favor of "{$name}". A constant has no $, never changes and is visible everywhere. const CURRENCY = 'USD'; is compiled, so it may appear only at top level or in a class; define() runs at run time and can sit inside an if. Since PHP 8.0 an undefined constant throws Error instead of being read as a string, and case-insensitive constants are gone.