PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 4 ■ ADVANCED FEATURES


function getAge() { return 44; }
function __toString() {
$desc = $this->getName();
$desc .= " (age ".$this->getAge().")";
return $desc;
}
}


Now when I print a Person object, the object will resolve to this:

$person = new Person();
print $person;


Bob (age 44)


The toString() method is particularly useful for logging and error reporting, and for classes
whose main task is to convey information. The Exception class, for example, summarizes exception data
in its
toString() method.


Callbacks, Anonymous Functions and Closures


Although not strictly an object-oriented feature, anonymous functions are useful enough to
mention here, because may encounter them in object-oriented applications that utilize callbacks.
What’s more, there have been some pretty interesting recent developments in this area.
To kick things off, here are a couple of classes:


class Product {
public $name;
public $price;


function __construct( $name, $price ) {
$this->name = $name;
$this->price = $price;
}
}


class ProcessSale {
private $callbacks;


function registerCallback( $callback ) {
if (! is_callable( $callback ) ) {
throw new Exception( "callback not callable" );
}
$this->callbacks[] = $callback;
}


function sale( $product ) {
print "{$product->name}: processing \n";
foreach ( $this->callbacks as $callback ) {
call_user_func( $callback, $product );
}

Free download pdf