PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 4 ■ ADVANCED FEATURES

So, why would you use a static method or property? Static elements have a number of
characteristics that can be useful. First, they are available from anywhere in your script (assuming that
you have access to the class). This means you can access functionality without needing to pass an
instance of the class from object to object or, worse, storing an instance in a global variable. Second, a
static property is available to every instance of a class, so you can set values that you want to be available
to all members of a type. Finally, the fact that you don’t need an instance to access a static property or
method can save you from instantiating an object purely to get at a simple function.
To illustrate this I will build a static method for the ShopProduct class that automates the
instantiation of ShopProduct objects. Using SQLite, I might define a products table like this:


CREATE TABLE products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT,
firstname TEXT,
mainname TEXT,
title TEXT,
price float,
numpages int,
playlength int,
discount int )


Now to build a getInstance() method that accepts a row ID and PDO object, uses them to acquire a
database row, and then returns a ShopProduct object. I can add these methods to the ShopProduct class I
created in the previous chapter. As you probably know, PDO stands for PHP Data Object. The PDO class
provides a common interface to different database applications.


// ShopProduct class...
private $id = 0;
// ...
public function setID( $id ) {
$this->id = $id;
}
// ...
public static function getInstance( $id, PDO $pdo ) {
$stmt = $pdo->prepare("select * from products where id=?");


$result = $stmt->execute( array( $id ) );


$row = $stmt->fetch( );


if ( empty( $row ) ) { return null; }


if ( $row['type'] == "book" ) {
$product = new BookProduct(
$row['title'],
$row['firstname'],
$row['mainname'],
$row['price'],
$row['numpages'] );
} else if ( $row['type'] == "cd" ) {
$product = new CdProduct(
$row['title'],
$row['firstname'],
$row['mainname'],
$row['price'],

Free download pdf