Object Oriented PHP: Part 4

In case you haven't been reading, here is the series so far:

Object Type Hints

In most programming languages, you can pass a value to a function. PHP is no different.


function PassMeSomething( $value ) {
print ($value);
}
// Prints value of $value when called

In addition to passing PHP functions values, in OOPHP, methods in objects can accept other objects. Let's start by building a new class.


class SalesItem {
public $brand;
public $name;
public $price = 0;
//
function __construct( $brand, $name, $price) {
$this -> brand = $brand;
$this -> name = $name;
$this -> price = $price;
}
//
function getBrandAndName() {
return "{$this -> brand}" . " {$this -> name}";
}
}

This class collects and stores the brand name, product name and price of a hypothetical product. Now let's create a new class that writes the information in the SalesItem class.


class WriteSalesItem {
public function write( $salesItem ) {
$str = $salesItem -> getBrandAndName();
$str = ', Now Only $';
$str .= $salesItem -> price;
print $str;
}
}

Now let's test the new class.


$item1 = new SalesItem( "Bob's", "Thingy", 12.49 );
$written = new WriteSalesItem()
$written -> write( $item1 );
// output:
// Bob's Thingy, Now Only $12.49

The WriteSalesItem class has one method that concatenates, formats and writes the values of the SalesItem class. The WriteSalesItem class required the SalesItem class to operate and won't work with other classes. That can become a problem, so how do we prevent it? We use class type hints, introduced in PHP 5.


class WriteSalesItem {
public function write( SalesItem $salesItem ) {
// ...
}
}

We amend the WriteSalesItem class to accept only instances of the class SalesItem. Now when we try to pass an object that isn't of the SalesItem class into the WriteSalesItem class, we get an error:


class SomethingElse { }
$written = new WriteSalesItem();
$written -> write( new SomethingElse() );
// output:
// Fatal error: Argument 1 must be an object of class SalesItem ...

Now we don't have to test the type of object being sent to WriteSalesItem before we try to use it. Also, a programmer using the WriteSalesItem class will immediately know what information it needs to operate. Just remember, class type hinting is only tested when the class is called, so be sure to test it and the methods it modifies before moving the class into production.

That takes care of things for this installment. You should now have a good feel for class type hints, next time we will cover Inheritance.

User login

Contacting Rob

Y! roberthenrylowe
AIM roberthenrylowe
ICQ 249971225
email rhlowe [at] gmail dot com

Networking Links