PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 4 ■ ADVANCED FEATURES

print ShopProduct::AVAILABLE;


Attempting to set a value on a constant once it has been declared will cause a parse error.
You should use constants when your property needs to be available across all instances of a class,
and when the property value needs to be fixed and unchanging.


Abstract Classes


The introduction of abstract classes was one of the major changes ushered in with PHP 5. Its inclusion in
the list of new features was another sign of PHP’s extended commitment to object-oriented design.
An abstract class cannot be instantiated. Instead it defines (and, optionally, partially implements)
the interface for any class that might extend it.
You define an abstract class with the abstract keyword. Here I redefine the ShopProductWriter class
I created in the previous chapter, this time as an abstract class.


abstract class ShopProductWriter {
protected $products = array();


public function addProduct( ShopProduct $shopProduct ) {
$this->products[]=$shopProduct;
}
}


You can create methods and properties as normal, but any attempt to instantiate an abstract object
will cause an error like this:


$writer = new ShopProductWriter();
// output:
// Fatal error: Cannot instantiate abstract class
// shopproductwriter ...


In most cases, an abstract class will contain at least one abstract method. These are declared, once
again, with the abstract keyword. An abstract method cannot have an implementation. You declare it in
the normal way, but end the declaration with a semicolon rather than a method body. Here I add an
abstract write() method to the ShopProductWriter class:


abstract class ShopProductWriter {
protected $products = array();


public function addProduct( ShopProduct $shopProduct ) {
$this->products[]=$shopProduct;
}


abstract public function write();
}


In creating an abstract method, you ensure that an implementation will be available in all concrete
child classes, but you leave the details of that implementation undefined.
If I were to create a class derived from ShopProductWriter that does not implement the write()
method like this:


class ErroredWriter extends ShopProductWriter{}


I would face the following error:

Free download pdf