Objects and PHP

Objects and PHP: Part II

On the previous page we introduced the important topic of objects and PHP; this time around we turn to more sophisticated aspects of this technology.

Extending classes

A popular aspect of object orientation is class extension, or inheritance, as it is sometimes known. Class extension allows PHP developers to add specific functions to otherwise generic classes. In non-trivial applications this is highly desirable, since it allows developers to store the program logic about a concept once and reuse it as many times as is required. Consider the following:

01	<?
02	class Vehicle
03	{
04		var $doors;
05		var $colour
06		var $name;
07		var $price;
09		function Vehicle($doors,$colour,$name,$price)
10		{
11			$this->doors = $doors;
12			$this->colour = $colour;
13			$this->name = $name;
14			$this->price = $price;
15		}
17		function print_vehstr()
18		{
19			echo "{$this->name}: {$this->colour} {$this->doors} door for \${$this->price}\n";
20		}
22		function commission()
23		{
24			return($this->price * 0.10);
25		}
26	}
28	class Motorbike extends Vehicle
29	{
30		var $colour;
31		var $name;
32		var $price;
34		function Motorbike($colour,$name,$price)
35		{
36			Vehicle::Vehicle(0,$colour,$name,$price);
37		}
39		function commission()
40		{
41			return(Vehicle::commission() * 0.5);
42		}
43	}
45	$a = new Motorbike("red","Zx-CL",10000);
46	echo "Commission on {$a->name} is \$".$a->commission()."\n";
47	?>

This script declares two classes, Vehicle and Motorbike. Vehicle is a generic class suitable for describing any kind of automobile - from a car to a motor bike. The reuse of code is obvious here: by extending the Vehicle class, the Motorbike class makes use of the existing logic and adds only code that differs from that which already exists.

To extend a class, developers need do only two things. First, the class that is being extended must already be declared. In our example, Vehicle is declared on line two and Motorbike is declared on line 28. Second, the 'extends' keyword needs to be used, so that PHP knows that the class being declared extends another class. This can be seen on line 28.

There are other interesting things about class extension. The constructor for Motorbike, declared on line 34, calls the constructor for Vehicle. It does this so that the variables $doors, $colour, $name and $price can be passed to the base or parent class, as it is often called. Notice that $doors is set to zero, since motor bikes do not have doors!

To call the constructor for Vehicle from Motorbike, we use a hitherto unseen PHP construct: '::'. The double colon allows PHP classes to refer directly to methods in another class without having to generate objects of them. Declaring the Motorbike constructor as follows is incorrect:

function Motorbike($colour,$name,$price)
$veh = new Vehicle(0,$colour,$name,$price);

This code actually creates a new object, $veh, which is local to the constructor. The rest of the class knows nothing about it. This is why the double colon syntax was introduced.

The final aspect of the Motorbike class that you should find interesting is this: Motorbike declares a method, commission(), which is used to calculate commission due to the sales person who sells the vehicle. However, this method is already declared in the parent class, Vehicle. This is not an error; rather, the method in Motorbike is said to overwrite the method in Vehicle.

This is convenient in our script. The commission() method in Vehicle calculates commission as 10 per cent of $price. The logic is different for motor bikes, however (see lines 39 to 42). Here, commission is calculated as being half that of other vehicles. If this was not possible, the commission() method would need to be named differently for the Motorbike class. This goes against the grain of object orientation, which focuses on efficiency and reuse of code.

Classes and objects are certainly a very useful aspect of PHP. The most valuable skill to learn is how to identify systems which take advantage of classes and objects.

Join the PC World newsletter!

Error: Please check your email address.
Rocket to Success - Your 10 Tips for Smarter ERP System Selection
Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Most Popular Reviews

Latest Articles


PCW Evaluation Team

Matthew Stivala

HP OfficeJet 250 Mobile Printer

The HP OfficeJet 250 Mobile Printer is a great device that fits perfectly into my fast paced and mobile lifestyle. My first impression of the printer itself was how incredibly compact and sleek the device was.

Armand Abogado

HP OfficeJet 250 Mobile Printer

Wireless printing from my iPhone was also a handy feature, the whole experience was quick and seamless with no setup requirements - accessed through the default iOS printing menu options.

Azadeh Williams

HP OfficeJet Pro 8730

A smarter way to print for busy small business owners, combining speedy printing with scanning and copying, making it easier to produce high quality documents and images at a touch of a button.

Andrew Grant

HP OfficeJet Pro 8730

I've had a multifunction printer in the office going on 10 years now. It was a neat bit of kit back in the day -- print, copy, scan, fax -- when printing over WiFi felt a bit like magic. It’s seen better days though and an upgrade’s well overdue. This HP OfficeJet Pro 8730 looks like it ticks all the same boxes: print, copy, scan, and fax. (Really? Does anyone fax anything any more? I guess it's good to know the facility’s there, just in case.) Printing over WiFi is more-or- less standard these days.

Ed Dawson

HP OfficeJet Pro 8730

As a freelance writer who is always on the go, I like my technology to be both efficient and effective so I can do my job well. The HP OfficeJet Pro 8730 Inkjet Printer ticks all the boxes in terms of form factor, performance and user interface.

Michael Hargreaves

Windows 10 for Business / Dell XPS 13

I’d happily recommend this touchscreen laptop and Windows 10 as a great way to get serious work done at a desk or on the road.

Featured Content

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?