Variables and constants

What a variable is

A variable is a named box for a value. The dollar sign marks the name, and the single equals sign stores the value:

$name = "Ada"; $age = 36; var_dump($name); // string(3) "Ada"

Variable naming rules

Names start with a letter or an underscore after the dollar sign, never with a digit. Names are case sensitive, so $name and $Name are two different boxes.

Digits may follow the first letter, but spaces and dashes never belong in a name. Pick short words that say what the value means:

$_total = 0; $userName = "ada";

Interpolation in strings

Double quoted strings replace variables with their values. This replacement is called interpolation:

$name = "Ada"; echo "Hello, $name!"; // Hello, Ada!

Single quoted strings never interpolate: they print the dollar sign and the name exactly as written:

$name = "Ada"; echo 'Hello, $name!'; // Hello, $name!

Constants with const

Constants hold values that never change. Define them once with const and write their names in capitals:

const SITE_NAME = "Aredel"; echo SITE_NAME; // Aredel

Unlike variables, constants need no dollar sign when you read them. Use them for settings that stay fixed, like titles and limits.

Next: Types in PHP

Автор статьи: Arthur Isaev

Изображение баннера