Monday, March 31, 2008

Class

You cannot have OOP without objects, and that is what classes provide. At the simplest level, a class is a data type. However, unlike primitive data types such as an integer, a float, or a character, a class is a complex, user-defined data type. A class is similar to a database record in that it encapsulates the characteristics of an object. For example, the record of a Person might contain a birth date, an address, a name, and a phone number. A class is a data type made up of other data types that together describe an object.

Classes Versus Records

Although a class is like a record, an important difference is that classes contain functions as well as different data types. And, when a function becomes part of a data type, procedural programming is turned on its head, quite literally, as you can see in the following example syntax. A function call that looked like this:


function_call($somevariable);

looks something like this with OOP:


$somevariable->function_call();

The significant difference here is that OO variables do not have things done to them, they do things. They are the actors rather than the acted upon, and for this reason they are said to behave. The behavior of a class is the sum of its functions.

A Cohesive Whole

Procedural programmers often work with code libraries. These libraries usually group related functions together. For instance, all database functions might be grouped together in a file called dbfunctions.inc. The functions that make up an object’s behavior should also be related to one another, but in a much stronger fashion than functions in the same library. Just as the different elements of a Person record describe an individual, so too should the behavior of a class describe the class. In order for something to be an object, it should be a cohesive whole incorporating appropriate characteristics and appropriate behavior.

Objects Are Instances

Classes are not themselves objects, but a way of creating objects-they are templates or blueprints that form the model for an object. When speaking loosely, these two terms are sometimes used interchangeably, but strictly speaking an object is an instance of a class. This is somewhat like the difference between the concept of an integer and a specific variable $X with a specific value. The concept of a class as a template for an object becomes clearer in the context of inheritance, especially when we discuss multiple inheritance (a topic we will deal with shortly).

No comments: