Welcome to the World of PHP Page 11

Object Orientation

What might be an object? We could say that the concept of a "car" is an object. A car can possess a number of variables -- a list of colors, model name, model year, manufacturer, wheel size, fuel capacity, invoice price, and so on. We could even imagine that this "car" object has some functions -- a function that determines dealer price based on invoice price and certain features, for example; or a function that determines fuel efficiency based on the variables of engine type and vehicle weight. The point is, all of this "stuff" is part of the "car" object.

In PHP, as in other object-oriented programming languages, you begin by creating a class, which is like a blueprint of an object. Rather than create a specific car object, for example, we create the outline of what a car object is and can contain.

class Car {
var $colors;
var $modelYear;
var $modelName;
var $modelMake;
var $invoice;
var $options; function dealerPrice ($carObject) {
#add the values of each option to the invoice price
while ( list($option,$cost)=each ($carObject->options) ) {
$subTotal += $cost;
return $carObject->invoice + $subTotal; }

Voila -- we've just created the blueprint, or class, for a car object. The object has four scalar variables and two arrays ($colors and $options), as well as one function. The function simply sums up any values in the $options array and adds the result to the invoice price, resulting in what we're calling the "dealer price" (a pure fiction!).

Blueprint in hand, we can build an actual car object, or what is known as an instance. Suppose we want to create an instance of a new Porsche Boxter:

$boxter = new Car;

We've instantiated the car class, and now own a new but empty $boxter object. To access variables within the object, use the -> constructor:

$boxter->modelMake="Porsche"; $boxter->invoice="85000";
$boxter->colors=array ("exterior"=>"red","interior"=>"black");
$boxter->options=array ("turbo"=>5000,"anti-theft"=>2500);

Assuming all values were in place, we could access the boxter object's function to calculate dealer cost:

if ($boxter->dealerPrice($boxter) > 90000) {
print "Sorry, you can't afford a
$boxter->modelYear $boxter->modelMake $boxter->modelName";


This article was originally published on Jul 7, 2000

Thanks for your registration, follow us on our social networks to keep up-to-date