The Building Blocks: Data Types, Literals, Variables, and Constants
The Building Blocks:
Data Types, Literals, Variables, and Constants
"One man's constant is another man's variable." —Alan Perlis
A program can do many things, including perform calculations, sort names, prepare phone lists, display images, play chess, ad infinitum. To do anything, however, the program works with the data that is given to it. Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within a program. PHP supports a number of fundamental basic data types, such as integers, floats, and strings. Basic data types are the simplest building blocks of a program. They are called scalars and can be assigned a single literal value such as a number,
5.7, or a string of characters, such as "
hello", a date and time, or a boolean (true/false). See Figure 4.1.
PHP also supports composite data types, such as arrays and objects. Composite data types represent a collection of data, rather than a single value (see Figure 4.2). The composite data types are discussed in Chapter 8, "Arrays," and Chapter 17, "Objects."
The different types of data are commonly stored in variables. Examples of PHP variables are $num = 5 or $name = "John" where variables $num and $name are assigned an integer and a string, respectively. Variables hold values that can change throughout the program, whereas once a constant is defined, its value does not change. PHP_VERSION and PHP_OS are examples of predefined PHP constants. The use of PHP variables and constants is addressed in "Variables" on page 70 and "Constants" on page 99 of this chapter.
PHP supports four core data types:
In addition to the four core data types, there are four other special types:
PHP supports both integers and floating-point numbers. See Example 4.1.
PHP numbers can be very large (the size depends on your platform), but a precision of 14 decimal digits is a common value or (~1.8e308).