The Building Blocks: Data Types, Literals, Variables, and Constants - Part 2 | WebReference

The Building Blocks: Data Types, Literals, Variables, and Constants - Part 2


[next]

The Building Blocks:
Data Types, Literals, Variables, and Constants - Part 2

By Ellie Quigley

Variables

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:

  1. Predefined variables
  2. User-defined variables
  3. Form variables related to names in an HTML form

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:

  • Numeric
  • String
  • Boolean
  • Objects
  • Arrays

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 $n and $x.

Valid Names

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, name, and NAme are all different variable names.

Table 4.2 Valid and Invalid Variable Name Examples

Valid Variable Names Invalid Variable Names
$name1$10names
$price_tagbox.front
$_abc$name#last
$Abc_22A-23
$A23$5

[next]

URL: