The Building Blocks: Data Types, Literals, Variables, and Constants - Part 2
The Building Blocks:
Data Types, Literals, Variables, and Constants - Part 2
Definition and Assignment
Variables are fundamental to all programming languages. They are data items that represent a memory storage location in the computer. Variables are containers that hold data such as numbers and strings. In PHP programs there are three types of variables:
Variables have a name, a type, and a value.
The values assigned to variables can change throughout the run of a program whereas constants, also called literals, remain fixed.
PHP variables can be assigned different types of data, including:
Computer programming languages like C++ and Java require that you specify the type of data you are going to store in a variable when you declare it. For example, if you are going to assign an integer to a variable, you would have to say something like:
and if you were assigning a floating-point number:
Languages that require that you specify a data type are called "strongly typed" languages. PHP, conversely, is a dynamically, or loosely typed, language, meaning that you do not have to specify the data type of a variable. In fact, doing so will produce an error. With PHP you would simply say:
and PHP will figure out what type of data is being stored in
Variable names consist of any number of letters (an underscore counts as a letter) and digits. The first letter must be a letter or an underscore (see Table 4.2). Variable names are case sensitive, so
NAme are all different variable names.
Table 4.2 Valid and Invalid Variable Name Examples
|Valid Variable Names||Invalid Variable Names|