• No results found

Introduction to OO Programming

In document Sams - Advanced Php Programming (Page 61-64)

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; echo hello($name);

echo You are .age($bday). years old.\n; echo goodbye($name);

? >

Introduction to OO Programming

It is important to note that in procedural programming, the functions and the data are separated from one another. In OO programming, data and the functions to manipulate the data are tied together in objects. Objects contain both data (called attributes or proper-ties) and functions to manipulate that data (called methods).

An object is defined by the class of which it is an instance. A class defines the attrib-utes that an object has, as well as the methods it may employ.You create an object by instantiating a class. Instantiation creates a new object, initializes all its attributes, and calls its constructor, which is a function that performs any setup operations. A class constructor in PHP5 should be named _ _constructor()so that the engine knows how to iden-tify it.The following example creates a simple class named User, instantiates it, and calls its two methods:

<?php class User {

public $name;

public $birthday;

public function _ _construct($name, $birthday) {

$this->name = $name;

$this->birthday = $birthday;

}

public function hello() {

39 Introduction to OO Programming

return Hello $this->name!\n; }

public function goodbye() {

return Goodbye $this->name!\n; }

public function age() {

$ts = strtotime($this->birthday);

if($ts === -1) { return Unknown; }

else {

$diff = time() - $ts;

return floor($diff/(24*60*60*365)) ; }

} }

$user = new User(george, 10 Oct 1973);

echo $user->hello();

echo You are .$user->age(). years old.\n; echo $user->goodbye();

?>

Running this causes the following to appear:

Hello george!

You are 29 years old.

Goodbye george!

The constructor in this example is extremely basic; it only initializes two attributes, name and birthday.The methods are also simple. Notice that $thisis automatically created inside the class methods, and it represents the Userobject.To access a property or method, you use the ->notation.

On the surface, an object doesn’t seem too different from an associative array and a collection of functions that act on it.There are some important additional properties, though, as described in the following sections:

n Inheritance—Inheritance is the ability to derive new classes from existing ones and inherit or override their attributes and methods.

n Encapsulation—Encapsulation is the ability to hide data from users of the class.

n Special Methods—As shown earlier in this section, classes allow for constructors that can perform setup work (such as initializing attributes) whenever a new object is created.They have other event callbacks that are triggered on other common events as well: on copy, on destruction, and so on.

n Polymorphism—When two classes implement the same external methods, they should be able to be used interchangeably in functions. Because fully understand-ing polymorphism requires a larger knowledge base than you currently have, we’ll put off discussion of it until later in this chapter, in the section “Polymorphism.”

Inheritance

You use inheritance when you want to create a new class that has properties or behav-iors similar to those of an existing class.To provide inheritance, PHP supports the ability for a class to extend an existing class.When you extend a class, the new class inherits all the properties and methods of the parent (with a couple exceptions, as described later in this chapter).You can both add new methods and properties and override the exiting ones. An inheritance relationship is defined with the word extends. Let’s extend User to make a new class representing users with administrative privileges.We will augment the class by selecting the user’s password from an NDBM file and providing a compari-son function to compare the user’s password with the password the user supplies:

class AdminUser extends User{

public $password;

public function _ _construct($name, $birthday) {

parent::_ _construct($name, $birthday);

$db = dba_popen(/data/etc/auth.pw, r, ndbm);

$this->password = dba_fetch($db, $name);

dba_close($db);

}

public function authenticate($suppliedPassword) {

if($this->password === $suppliedPassword) { return true;

} else {

return false;

} } }

Although it is quite short,AdminUserautomatically inherits all the methods from User, so you can call hello(),goodbye(), andage(). Notice that you must manual-ly call the constructor of the parent class as parent::_ _constructor(); PHP5 does not automatically call parent constructors.parentis as keyword that resolves to a class’s parent class.

41 Introduction to OO Programming

Encapsulation

Users coming from a procedural language or PHP4 might wonder what all the public stuff floating around is.Version 5 of PHP provides data-hiding capabilities with public, protected, and private data attributes and methods.These are commonly referred to as PPP (for public, protected, private) and carry the standard semantics:

n Public—A public variable or method can be accessed directly by any user of the class.

n Protected—A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.

n Private—A private variable or method can only be accessed internally from the class in which it is defined.This means that a private variable or method cannot be called from a child that extends the class.

Encapsulation allows you to define a public interface that regulates the ways in which users can interact with a class.You can refactor, or alter, methods that aren’t public, with-out worrying abwith-out breaking code that depends on the class.You can refactor private methods with impunity.The refactoring of protected methods requires more care, to avoid breaking the classes’ subclasses.

Encapsulation is not necessary in PHP (if it is omitted, methods and properties are assumed to be public), but it should be used when possible. Even in a single-programmer environment, and especially in team environments, the temptation to avoid the public interface of an object and take a shortcut by using supposedly internal methods is very high.This quickly leads to unmaintainable code, though, because instead of a simple public interface having to be consistent, all the methods in a class are unable to be refac-tored for fear of causing a bug in a class that uses that method. Using PPP binds you to this agreement and ensures that only public methods are used by external code, regard-less of the temptation to shortcut.

In document Sams - Advanced Php Programming (Page 61-64)