Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ......

27
Chapter 7 WRITING PROGRAMS WITH OBJECTS

Transcript of Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ......

Page 1: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Chapter 7WRITING PROGRAMS WITH OBJECTS

Page 2: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Chapter ObjectiveUse a custom class to build enhanced web pages

Design a basic class of your own

Build an instance of a class

Leverage inheritance, encapsulation, and polymorphism

Create properties and methods in your classes

Understanding Object-Oriented Programming (OOP)

Extensive example using the SuperHTML class

Page 3: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Understanding Object-Oriented Programming (OOP)We live in a world of objects - things that we perceive. Object-oriented programming languages, like PHP 5, allow us to model these real-world objects with software objects.

For example, we could create a software object called myPen which represents my pen. Thus, OOP is more natural, simpler, and easier to understand, compared to traditional, procedure-oriented languages like C.

Page 4: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Understanding Object-Oriented Programming (OOP)

With a procedure-oriented language you try to make the real-world problem you're attempting to solve fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This is unnatural and limiting. With an object-oriented language you create a data type, called a class, for every kind of thing that exists in the problem. You can still have ints, floats, strings, and arrays; but you can also have pens, paper, sentences, stories, authors, cars, motorcycles, people, buildings, clouds, dogs, angles, students, courses, bank accounts, and any other kind or type of thing that's important to your problem.

A class definition consists of a set of properties and behavior, called methods/functions, possessed by all things, that is objects, of a given kind. Since all pens have ink color, we will include aninkColor property in our Pen class. And since all pens can be used to write, we will include a write() function.

Page 5: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Understanding Object-Oriented Programming (OOP)

In PHP, a Pen class could be defined as follows:

class Pen {

// properties

var $inkColor = 'black'; // default ink color is black

// methods

function setInkColor($color) {

$this->inkColor = $color;

} // end setInkColor

function write($what) {

echo $what;

} // end write

} // end Pen

Page 6: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Understanding Object-Oriented Programming (OOP)

A class is a programmer-defined type that serves as a blueprint for creating objects of a certain kind. Once you have defined a class with its properties and methods, you can use it to create any number of objects. A common analogy is that a class is to an object as a cookie cutter is to a cookie. One cookie cutter can be used to make many cookies. Similarly, one class can be used to create many objects. In the following two statements, we use the Pen class to create two Pen objects:

$myPen = new Pen(); // first Pen object

$yourPen = new Pen(); // second Pen object

All Pen objects, such as $myPen, have the properties and methods defined in the Pen class. We could use the write()method to write Hello, world! with myPen as follows:

$myPen->write('Hello, world!'); // greet the world

All objects of a given class have the same properties and methods. However, the properties may have different values. For example,

$myPen->setInkColor('red'); // only the teacher gets to use red ink

$yourPen->setInkColor('blue'); // student must use some other color ink

Page 7: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Four Key Principles of OOP: AbstractionAbstraction, or classification, is something we humans do naturally. We see a lot of similar looking things and refer to them with the same word. For example, we notice a lot of tall, leafy, green plants with woody trunks and refer to them as trees. So, in OOP we could define a Tree class (class names begin with a capital letter, by convention) and then we could create Treeobjects. When we define our Tree class, we specify properties and methods/functions. Real-world objects have many properties and methods/behavior. For our software model, we choose the ones that are relevant and important for our purposes. For example, for our Tree class we may decide to choose the following properties: height, leafShape, leafColor, trunkDiameter, age.

Page 8: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Four Key Principles of OOP: EncapsulationAn object is like a nut or capsule with a delicate interior protected by a hard outer shell. The object's interior is its state - the properties and their values. The outer shell is the object's interface - the methods available to client programmers. The object's state is hidden within the protective custody of its methods.

Good OOP practice dictates that client programmers use only the object's methods to manipulate its state; they should not access the properties directly. For example, to change the writing color of myPen, one should use the following statement:

$myPen->setInkColor(‘black'); // set out pen Ink Color

Page 9: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Four Key Principles of OOP: EncapsulationThis practice of using the methods (the public interface) to access the properties (the private state) guarantees that the object's integrity is preserved. It also gives the class designer the freedom to modify the interior design and implementation of the class without breaking client code.

The principle of encapsulation has two key benefits:

Modularity - classes and objects are maintained as a unit and accessed as a unit.

Information hiding – classes and objects have a public interface and private implementation.

Page 10: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Four Key Principles of OOP: InheritanceA subclass (aka derived class) can extend an existing (aka base) class. The subclass is a specialization of the base class. For example, we could define a BallpointPen class that extends the Pen class. Pen is said to be a superclass (aka parent class) of the BallpointPen class. In PHP, the syntax for defining a subclass is

class BallpointPen extends Pen { ...}

The subclass inherits all the properties and methods from the superclass. For example, the BallpointPen class inherits $inkColor and write() from the Pen class.

As another example, If PineTree extends the Tree class, and the Tree class has an $age property and a grow() method, then PineTree would inherit $age and grow().

Note that a ballpoint pen is a type of pen, and a pine tree is a type of tree. Thus, we say that the subclass has an IS A relationship with the superclass.

Page 11: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Four Key Principles of OOP: PolymorphismAn object of a given class can be used anywhere an object of its superclass can be used, because, as we just saw, the object IS A object of the superclass. For example, if we have the following code

$myPen = new BallpointPen();

$myPen->write('Hello, world!'); // greet the world

the code still works because myPen is also a Pen. So, myPen has multiple types (BallpointPen and Pen). It is polymorphic (many shaped).

Page 12: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Class, Object, MessageClass

A class defines all the properties and methods common to all objects of a certain kind. A class can be likened to a factory, stamp, blueprint, or cookie cutter.

Object

An object, also called an instance of a class, is an area in memory that contains the name of the class to which it belongs along with the properties and their values. An object can be likened to the gadget manufactured, the imprint produced by the stamp, the thing constructed from the blueprint, or the cookie formed by the cookie cutter.

Message

An object-oriented program consists of a set of objects sending messages to each other. In PHP, the message format is

receivingObject->methodName(arguments);

In the following message

$myPen->write('Hello, world!'); // greet the world

the receivingObject is $myPen, the methodName is write, and there is one argument 'Hello, world!'

Page 13: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Introducing the SuperHTML Object

Page 14: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Building a Simple Document with SuperHTMLThe author of the textbook created the SuperHTML Object to demo OOP prinicples.

The SuperHTML object is a special type of entity that allows you to automatically create and modify a web page.

Page 15: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Building a Simple Documents with SuperHTML

The include statement retrieves data from another file and interprets it as HTML code. In this example SuperHTMLDef.php contains the definition for the SuperHTML object.

It is not required to completely understand a Object to use it.

The next line creates a new variable called $s: $s = new SuperHTML("Basic Super Page");

Page 16: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Building the Web PageSince $s = new SuperHTML("Basic Super Page"); is an object, it has certain characteristics, called properties, and it has certain behaviors, called methods. By invoking the object’s methods, you can do anything the object has pre-included without a lot of work for yourself.

Both buildTop() and buildBottom() are considered methods, which are simply functions associated with a particular object type. Because $s

is a uperHTML object, it knows how to build the top and bottom of the

web page.

Page 17: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Textbook Example: SuperHTML MethodsBUILDTOP() BUILDBOTTOM()

The buildTop() and buildBottom() directives feel a lot like function calls, because they are very similar to the functions you’ve already created and used many times.

However, these functions are designed to work within the context of a particular

object. A function attached to an object is referred to as a method of the object.

Page 18: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Write Out Page

buildTop() nor buildBottom prepare the HTML page as a long string property inside the SuperHTML object.

SuperHTML has a method called getPage() that returns the actual HTML code for the page

GETPAGE() RETURN STRING

Page 19: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Creating a Basic ObjectCLASS CRITTER W/ ONE VARIABLE

CREATE OBJECT CRITTER – SET OBJECT VARIABLE NAME

Page 20: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Defining the Simple Critter ClassThe class keyword indicates that I am defining a class.

A class is a design or template for something.

This code created a new variable called $theCritter and used the “new” keyword to indicate that a new instantiate of object Critter will be created.

Now theCritter object can be manipulated, such as assign a value to the name property.

Page 21: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Adding a Method to a ClassTo make a class more functional, it needs to have some sort of behavior as well as data. This is where methods come in.

Note: It indicates that the specified variable can only be referred to inside the objectafterthe object is created, you can no longer directly access the name property directly. Instead, you’ll use special methods to modify and retrieve the name.

Page 22: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

ConstructorThe first function defined in most classes is called the constructor. Constructors are special methods used to build an object. Any code you want to occur when the object first appears should go in the constructor. Most often you use the constructor to initialize your properties, so I do that for the Critter class:

function __construct($handle = "anonymous"){

$this->name = $handle;

} // end constructor

To specify that a function is a class constructor, it should be called __construct. (That’s construct preceded by two underscores.)

Guarantees that the name

property willhave a value.

Page 23: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Property SetterThe setName() method is an example of a property access method that allows you to change a property through a method.

Setter methods usually begin with set and they always accept a parameter. The parameter is the value the user wants to change.

Page 24: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Getter MethodThe getName() method simply returns the value of the appropriate property. This is useful because you might have different ways of returning the same value.

Note: The variable name is a “private” variable in the Critter class. To get the value of name, a getter Method must be used.

Page 25: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

Inheriting from a Parent Class

Inheritance is used to build on previous work and add new features to it. It is used to build common functionality and at the same time allow variation.

These subclasses incorporate additions or deviations from the basic behavior.

Defined the GlitterCritter class just like any other class, except for the extends keyword:

◦ class GlitterCritter extends Critter{

Unless indicated otherwise, the GlitterCritter class will act just like an ordinary Critter. It automatically inherits all properties, methods, and even the constructor from the parent class. The extends keyword indicates that the GlitterCritter is an extension or improvement of the Critter class. I added two methods to the class. One brand new method is called glow().

The program begins by including the previously designed Critter class.

defined the GlitterCritterclass just like any other

class, except for the extends keyword.

Page 26: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

BUILDING THE SUPERHTML CLASSFor a larger more complex Class, read “Building the SuperHTML Class”

Page 285

Page 27: Chapter 7 · Use a custom class to build enhanced web pages Design a basic class of your own ... fit a few, pre-determined data types: integers, floats, strings, arrays, etc. This

SummaryThis chapter introduced the basic concepts of object-oriented programming.

You learned how objects implement inheritance, polymorphism, and encapsulation. You experimented with the SuperHTML class and learned how to expand it when creating your own useful and powerful object classes.