Saturday, November 1, 2008

Variables

As a byproduct of examining the examples up to this point, I’ve introduced you to how variables are assigned and manipulated. However, it would be wise to explicitly
lay the groundwork as to how variables are declared and manipulated. The coming sections will examine these rules in detail.

Variable Declaration


A variable is a named memory location that contains data that may be manipulated throughout the execution of the program. A variable always begins with a dollar sign, $. The following are all valid variables:
$color
$operating_system
$_some_variable
$model
Variable names follow the same naming rules as those set for identifiers. That is, a variable name can begin with either an alphabetical letter or underscore and
can consist of alphabetical letters, underscores, integers, or other ASCII characters ranging from 127 through 255. Interestingly, variables do not have to be explicitly declared in PHP, much as is the case with the Perl language. Rather, variables can be declared and assigned values simultaneously. Furthermore, a variable’s data type is implicitly determined by examining the kind of data that the variable holds. Consider the following example:
$sentence = "This is a sentence."; // $sentence evaluates to string.
$price = 42.99; // $price evaluates to a floating-point
$weight = 185; // $weight evaluates to an integer.
You can declare variables anywhere in a PHP script. However, the location of the declaration greatly influences the realm in which a variable can be accessed. This access domain is known as its scope.

Variable Scope


Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:
Local variables
• Function parameters
• Global variables
• Static variables

No comments: