Variable Declaration in PHP

Author
By Darío Rivera
Posted On in PHP

Variables in PHP are declared by preceding the variable name with the dollar sign ( $ ). Next, we will see some rules to keep in mind for variable naming.

Naming Rules

Case-Sensitivity: All variable names are case-sensitive, which means that the variable $num is different from the variable $Num.

Label-Rule: Variable names must start with a letter or an underscore ( _ ), followed by a combination of letters, numbers, or underscores. When it comes to letters in this case, it includes not only a-z and A-Z but also bytes from 128 to 255 (0x80-0xff).

Declaration and Initialization

In PHP, variables are always declared and initialized in one statement. It is also not necessary to indicate the data type that the variable will contain. Let's see how to declare and initialize different types of variables.

// this variable will be of type string
$name = 'Bob';

// this variable will be of type integer
$age = 78;

// this variable will be of type double
$height = 168.7;

Now take a look at these variable declarations, some are correct and some are incorrect. In each case, the reason is explained with a PHP comment before the declaration.

// invalid, starts with a number
$4site = 'not yet';

// valid; starts with underscore
$_4site = 'not yet';

// valid; 'ä' is an extended ASCII character (ASCII 228)
$täyte = 'mansikka';

That's all for our post on declaration and initialization. There are many other peculiarities regarding variable assignment that we will see as our PHP series progresses. See you soon!


Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.