PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 3 ■ OBJECT BASICS


■Note PHP 4 does not recognize visibility keywords for methods or properties. Adding public, protected, or


private to a method declaration will cause a fatal error. All methods in PHP 4 are implicitly public.


In most circumstances, you will invoke a method using an object variable in conjunction with ->
and the method name. You must use parentheses in your method call as you would if you were calling a
function (even if you are not passing any arguments to the method).


class ShopProduct {
public $title = "default product";
public $producerMainName = "main name";
public $producerFirstName = "first name";
public $price = 0;


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


$product1 = new ShopProduct();
$product1->title = "My Antonia";
$product1->producerMainName = "Cather";
$product1->producerFirstName = "Willa";
$product1->price = 5.99;


print "author: {$product1->getProducer()}\n";


This outputs the following:

author: Willa Cather


I add the getProducer() method to the ShopProduct class. Notice that I do not include a visibility
keyword. This means that getProducer() is a public method and can be called from outside the class.
I introduce a feature in this method. The $this pseudo-variable is the mechanism by which a class
can refer to an object instance. If you find this concept hard to swallow, try replacing $this with “the
current instance.” So the statement


$this->producerFirstName


translates to


the $producerFirstName property of the current instance

Free download pdf