Saturday, 18 December 2010

PHP’s Supported Data Types

A datatype is the generic name assigned to any data sharing a common set of characteristics.

Common data types include Boolean, integer, float, string, and array

Scalar Data Types are used to represent a single value. Several data types fall under this category, including Boolean, integer, float, and string.

Boolean

The Boolean data type represents truth, supporting only two values: TRUE and FALSE (case insensitive). Alternatively, we can use zero to represent FALSE, and any nonzero value to represent TRUE. A few examples follow:



Integer

An integer is representative of any whole number or, in other words, a number that does not contain fractional parts. PHP supports integer values represented in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal) numbering systems, although it’s likely we’ll only be concerned with the first of those systems. Several examples follow:


The maximum supported integer size is platform-dependent, although this is typically positive or negative 2^31 for PHP version 5 and earlier. PHP 6 introduced a 64-bit integer value, meaning PHP will support integer values up to positive or negative 2^63 in size.

Float

Floating-point numbers, also referred to as floats, doubles, or real numbers, allow us to specify numbers that contain fractional parts. Floats are used to represent monetary values, weights, distances, and a whole host of other representations in which a simple integer value won’t suffice. PHP’s floats can be specified in a variety of ways, several of which are demonstrated here:


String

Simply put, a string is a sequence of characters treated as a contiguous group. Strings are delimited by single or double quotes, although PHP also supports another delimitation methodology, which is introduced in the later “String Interpolation” section.
The following are all examples of valid strings:


Compound Data Types

Compound data types allow for multiple items of the same type to be aggregated under a single representative entity. The array and the object fall into this category.

Array


It’s often useful to aggregate a series of similar items together, arranging and referencing them in some specific way. This data structure, known as an array, is formally defined as an indexed collection of data values. Each member of the array index (also known as the key) references a corresponding value and can be a simple numerical reference to the value’s position in the series, or it could have some direct correlation to the value.

For example, if we were interested in creating a list of cities in Vietnam, we could use
a numerically indexed array, like so:


But what if the project required correlating the list of city to their famous sightseeing? Rather than base the keys on a numerical index, we might instead use an associative index, like this:


Object

The object is a central concept of the object-oriented programming paradigm.
Unlike the other data types contained in the PHP language, an object must be explicitly declared. This declaration of an object’s characteristics and behavior takes place within something called a class.



A class definition creates several attributes and functions pertinent to a data structure, in this case a data structure named Appliance. There is only one attribute, power, which can be modified by using the method setPower().

Converting Between Data Types Using Type Casting

Converting values from one datatype to another is known as type casting.
A variable can be evaluated once as a different type by casting it to another.
This is accomplished by placing the intended type in front of the variable to be cast.




Let’s consider several examples. Suppose we’d like to cast an integer as a double:


Output will be 13.0

Type casting a double to an integer will result in the integer value being rounded down, regardless of the decimal value. Here’s an example:


What happens if we cast a string datatype to that of an integer? Let’s find out:



Output will return to 0 (zero).

We can also cast a datatype to be a member of an array. The value being cast simply becomes the first element of the array:


Output will be 1985

Note that this shouldn’t be considered standard practice for adding items to an array because this only seems to work for the very first member of a newly created array. If it is cast against an existing array, that array will be wiped out, leaving only the newly cast value in the first position.

Any datatype can be cast as an object. The result is that the variable becomes an attribute of the object, the attribute having the name scalar:


The result is BMW

Adapting Data Types with Type Juggling


Variables are sometimes automatically cast to best fit the circumstances in which they are referenced. Consider the following snippet:


The outcome is the expected one; $total is assigned 20, converting the $count variable from a string to an integer in the process.

Here’s another example demonstrating PHP’s type-juggling capabilities:


The integer value at the beginning of the original $total string is used in the calculation. However, if it begins with anything other than a numerical representation, the value is 0. Let's consider another example:


In this example, a string is converted to Boolean type in order to evaluate the if statement.

Let's consider one last particularly interesting example. If a string used in a mathematical calculation includes ., e, or E (representing scientific notation), it will be evaluated as a float:


Variables

A variable is a symbol that can store different values at different times.

For example, suppose we create a web-based calculator capable of performing mathematical tasks. Of course, the user will want to input values of his choosing; therefore, the program must be able to dynamically store those values and perform calculations accordingly. At the same time, the programmer requires a user-friendly means for referring to these value-holders within the application. The variable accomplishes both tasks.

Variable Declaration
A variable always begins with a dollar sign, $, which is then followed by the variable name.
Variable names follow the same naming rules as identifiers.
That is, a variable name can begin with either a letter or an underscore and can consist of letters, underscores, numbers, or other ASCII characters ranging from 127 through 255.

The following are all valid variables:
  • $color
  • $operating_system
  • $_vai_variable
  • $kieuCach
Note that variables are case sensitive. For instance, the following variables bear no relation to each other:
  • $color
  • $Color
  • $COLOR
Value Assignment
Assignment by value simply involves copying the value of the assigned expression to the variable assignee. This is the most common type of assignment.

A few examples follow:
  • $color = "red";
  • $number = 12;
  • $age = 12;
  • $sum = 12 + "15"; // $sum = 27
Each of these variables possesses a copy of the expression assigned to it.
For example, $number and $age each possesses their own unique copy of the value 12.

Reference Assignment
the ability in PHP to assign variables by reference, which essentially means that you can
create a variable that refers to the same content as another variable does.

We can assign variables by reference by appending an ampersand (&) to the equal sign.

Example:

An alternative reference-assignment syntax is also supported, which involves appending the
ampersand to the front of the variable being referenced.

The following example adheres to this new syntax:


Variable Scope
We can declare our variables (by value or by reference) anywhere in a PHP script.

The location of the declaration greatly influences the realm in which a variable can be accessed. This accessibility domain is known as its scope.

PHP variables can be one of four scope types:
  • Local variables
  • Function parameters
  • Global variables
  • Static variables
Local Variables
A variable declared in a function is considered local. it can be referenced only in that function.

Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function.

Note that when we exit the function in which a local variable has been declared, that variable and its corresponding value are destroyed.

Local variables are helpful because they eliminate the possibility of unexpected side effects that can result from globally accessible variables that are modified, intentionally or not. Consider this listing:



Executing this listing results in the following:



Two different values for $x are output. This is because the $x located inside the assignx() function is local.
Modifying the value of the local $x has no bearing on any values located outside of the function.
On the same note, modifying the $x located outside of the function has no bearing on any variables contained in assignx().

Function Parameters
Any function that accepts arguments must declare those arguments in the function header. Although those arguments accept values that come from outside of the function, they are no longer accessible once the function has exited.

Function parameters are declared after the function name and inside parentheses (dấu ngoặc) . They are declared much like a typical variable would be:



Global Variables

In contrast to local variables, a global variable can be accessed in any part of the program.
To modify a global variable, however, it must be explicitly (rõ ràng) declared to be global in the function in which it is to be modified.
By placing the keyword global in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. Consider an example:



The displayed value of $somevar would be 16.

However, if we were to omit this line, global $somevar; then the variable $somevar would be assigned the value 1 because $somevar would then be considered local within the addit() function. This local declaration would be implicitly set to 0 and then incremented by 1 to display the value 1.

An alternative method for declaring a variable to be global is to use PHP’s $GLOBALS array.
Reconsidering the preceding example, we can use this array to declare the variable $somevar to be global:



This returns the following:



Static Variables
In contrast to the variables declared as function parameters, which are destroyed on the function’s exit, a static variable does not lose its value when the function exits and will still hold that value if the function is called again.

We can declare a variable as static simply by placing the keyword static in front of the variable name, like so:

STATIC $somevar;

Consider an example:



There will be 2 different cases that may result.
If the variable $count was not designated to be static (thus making $count a local variable), the outcome would be as follows:



Another case with variable $count which is static, it retains its previous value each time the function is executed. Therefore, the outcome is the following:



Static scoping is particularly useful for recursive functions (hàm đệ quy), a powerful programming concept in which a function repeatedly calls itself until a particular condition is met.