ServersWelcome to the World of PHP Page 11

Welcome to the World of PHP Page 11

ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.




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
$subTotal=0;
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->modelYear=1999;
$boxter->modelName="Boxter";
$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";
}


NEXT ->

Get the Free Newsletter!

Subscribe to Daily Tech Insider for top news, trends & analysis

Latest Posts

Related Stories