PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

C H A P T E R 4


■ ■ ■


Advanced Features


You have already seen how class type hinting and access control give you more control over a class’s
interface. In this chapter, I will delve deeper into PHP’s object-oriented features.
This chapter will cover



  • Static methods and properties: Accessing data and functionality through classes
    rather than objects

  • Abstract classes and interfaces: Separating design from implementation

  • Error handling: Introducing exceptions

  • Final classes and methods: Limiting inheritance

  • Interceptor methods: Automating delegation

  • Destructor methods: Cleaning up after your objects

  • Cloning objects: Making object copies

  • Resolving objects to strings: Creating a summary method

  • Callbacks: Adding functionality to components with anonymous functions


Static Methods and Properties


All the examples in the previous chapter worked with objects. I characterized classes as templates from
which objects are produced, and objects as active components, the things whose methods you invoke
and whose properties you access. I implied that, in object-oriented programming, the real work is done
by instances of classes. Classes, after all, are merely templates for objects.
In fact, it is not that simple. You can access both methods and properties in the context of a class
rather than that of an object. Such methods and properties are “static” and must be declared as such by
using the static keyword.


class StaticExample {
static public $aNum = 0;
static public function sayHello() {
print "hello";
}
}

Free download pdf