PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

C H A P T E R 3


■ ■ ■


Object Basics


Objects and classes lie at the heart of this book, and since the introduction of PHP 5, they lie at the heart
of PHP too. In this chapter, I lay down the groundwork for more in-depth work with objects and design
by examining PHP’s core object-oriented features.
PHP 5 brought with it a radical advance in object-oriented support, so if you are already familiar
with PHP 4, you will probably find something new here. If you are new to object-oriented programming,
you should read this chapter carefully.
This chapter will cover



  • Classes and objects: Declaring classes and instantiating objects

  • Constructor methods: Automating the setup of your objects

  • Primitive and class types: Why type matters

  • Inheritance: Why we need inheritance and how to use it

  • Visibility: Streamlining your object interfaces and protecting your methods and
    properties from meddling


Classes and Objects


The first barrier to understanding object-oriented programming is the strange and wonderful
relationship between the class and the object. For many people it is this relationship that represents the
first moment of revelation, the first flash of object-oriented excitement. So let’s not skimp on the basics.


A First Class


Classes are often described in terms of objects. This is interesting, because objects are often described in
terms of classes. This circularity can make the first steps in object-oriented programming hard going.
Since classes define objects, we should begin by defining a class.
In short, a class is a code template used to generate objects. You declare a class with the class
keyword and an arbitrary class name. Class names can be any combination of numbers and letters,
although they must not begin with a number. The code associated with a class must be enclosed within
braces. Let’s combine these elements to build a class.


class ShopProduct {
// class body
}

Free download pdf