Have an account? Sign in
Login  Register  Facebook
This Page is Under Construction! - If You Want To Help Please Send your CV - Advanced Web Core (BETA)
Quick Table of Contents
[Edit] 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 you were interested in creating a list of U.S. states, you could use a numerically indexed array, like so:
$state[0] = "Alabama";
$state[1] = "Alaska";
$state[2] = "Arizona";
...
$state[50] = "Wyoming";
But what if the project required correlating U.S. states to their capitals? Rather than base the keys on a numerical index, you might instead use an associative index, like this:
$state["Alabama"] = "Montgomery";
$state["Alaska"] = "Juneau";
$state["Arizona"] = "Phoenix";
...
$state["Wyoming"] = "Cheyenne";

Object

The other compound datatype supported by PHP is the object. The object is a central concept of the object-oriented programming paradigm. If you’re new to object-oriented programming, Chapters 6 and 7 are devoted to the topic. 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. Here’s a general example of a class definition and subsequent invocation:
class Appliance {
private $_power;
function setPower($status) {
$this->_power = $status;
}
}
$blender = new Appliance;
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(). Remember, however, that a class definition is a template and cannot itself be manipulated. Instead, objects are created based on this template. This is accomplished via the new keyword. Therefore, in the last line of the previous listing, an object of class Appliance named blender is created. The blender object’s power attribute can then be set by making use of the method setPower():
$blender->setPower("on");
September 12, 2011