PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 3 ■ OBJECT BASICS

So getProducer() combines and returns the $producerFirstName and $producerMainName properties,
saving me from the chore of performing this task every time I need to quote the full producer name.
This has improved the class a little. I am still stuck with a great deal of unwanted flexibility, though. I
rely on the client coder to change a ShopProduct object’s properties from their default values. This is
problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder
will thank you for that. Second, I have no way of ensuring that any of the properties are set when a
ShopProduct object is initialized. What I need is a method that is called automatically when an object is
instantiated from a class.


Creating a Constructor Method


A constructor method is invoked when an object is created. You can use it to set things up, ensuring that
essential properties are set, and any necessary preliminary work is completed. In versions previous to
PHP 5, constructor methods took on the name of the class that enclosed them. So the ShopProduct class
would use a ShopProduct() method as its constructor. Although this still works, as of PHP 5, you should
name your constructor method __construct(). Note that the method name begins with two underscore
characters. You will see this naming convention for many other special methods in PHP classes. Here I
define a constructor for the ShopProduct class:


class ShopProduct {
public $title;
public $producerMainName;
public $producerFirstName;
public $price = 0;


function __construct( $title,
$firstName, $mainName, $price ) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}


function getProducer() {
return "{$this->producerFirstName}".
" {$this->producerMainName}";
}


}


Once again, I gather functionality into the class, saving effort and duplication in the code that uses
it. The __construct() method is invoked when an object is created using the new operator.


$product1 = new ShopProduct( "My Antonia",
"Willa", "Cather", 5.99 );
print "author: {$product1->getProducer()}\n";


This produces

author: Willa Cather

Free download pdf