Приглашаем посетить
Есенин (esenin-lit.ru)

Chapter 2.  Object-Oriented Programming Through Design Patterns

Previous
Table of Contents
Next

2. Object-Oriented Programming Through Design Patterns

BY FAR THE LARGEST AND MOST HERALDED change in PHP5 is the complete revamping of the object model and the greatly improved support for standard object-oriented (OO) methodologies and techniques. This book is not focused on OO programming techniques, nor is it about design patterns. There are a number of excellent texts on both subjects (a list of suggested reading appears at the end of this chapter). Instead, this chapter is an overview of the OO features in PHP5 and of some common design patterns.

I have a rather agnostic view toward OO programming in PHP. For many problems, using OO methods is like using a hammer to kill a fly. The level of abstraction that they offer is unnecessary to handle simple tasks. The more complex the system, though, the more OO methods become a viable candidate for a solution. I have worked on some large architectures that really benefited from the modular design encouraged by OO techniques.

This chapter provides an overview of the advanced OO features now available in PHP. Some of the examples developed here will be used throughout the rest of this book and will hopefully serve as a demonstration that certain problems really benefit from the OO approach.

OO programming represents a paradigm shift from procedural programming, which is the traditional technique for PHP programmers. In procedural programming, you have data (stored in variables) that you pass to functions, which perform operations on the data and may modify it or create new data. A procedural program is traditionally a list of instructions that are followed in order, using control flow statements, functions, and so on. The following is an example of procedural code:

<?php
function hello($name)
{
  return "Hello $name!\n";
}
function goodbye($name)
{
  return "Goodbye $name!\n";
}
function age($birthday) {
  $ts = strtotime($birthday);
  if($ts === -1) {
    return "Unknown";
  }
  else {
    $diff = time() - $ts;
    return floor($diff/(24*60*60*365));
  }
}
$name = "george";
$bday = "10 Oct 1973";
print hello($name);
print "You are ".age($bday)." years old.\n";
print goodbye($name);
? >


Previous
Table of Contents
Next