Dr. Logan | COM Courses | Syllabus | Reading Notes

Objects

What do you mean, OOP's? Object-oriented Programming takes the notion of separate code files and functions a little further, introducing its own nerdy nomenclature in the process. If you think of Objects as things like functions, it helps. Think of objects as things that do things, use things, and have options in the doing or using. Or, think of objects in a grammatical sense as though they are made up of verbs (actions), nouns (things), or adjectives and adverbs (modifiy nouns and verbs), and the new jargon may start to make sense. Essentially, view an object as a mysterious box: You need to know the name of the box, what it does, what you need to give it and what it will give back, and whether there are any other things that you can give the box to tweak how it works. The new vocabulary will relabel verbs / actions as methods and nouns and modifiers as attributes or collections.

Objects allow us to develop pieces of code that we can text and reuse, like a function. Usually, we build or use a large number of objects, previously written. When we use an object that has been carefully developed and tested by ourselves or (more commonly) someone else, the object is likely to be more reliable (previously debugged) and it will save us time, often an enormous amount of time. We can, for instance, take a week and write a few hundred lines of code to create an events calendar for our client, or we can search for any of several previously-written calendar objects that do the same thing for us. Custom-written code is one thing, but reinventing the wheel is a waste.

In programming, an object is something you can describe through a set of design specifications. The complete set of specs, also referred to as a class, defines the object. Texts often use telephone or car object metaphors. Defining a class for the object would allow you to say what physical properties it has, how it works, and what it can do.

• The telephone is a plastic and metal device with numbers to dial and a handset to listen to and talk into; it has a telephone number that others can use to reach only you, and it lets you use other people's unique numbers to reach only them; it rings when someone wants to talk to you, and it shuts itself off when you hang it up.

• A car is a plastic and metal device with a unique license number and a seat that you sit in while you are talking on your telephone; it has a gas peddle to let you go fast and a break peddle to let you go slow; the wheels go fast when you step on the gas and slow when you step on the break, and the whole thing gets crumpled if you get gas and break confused because you are talking on your telephone.

(Some objects are not meant to be used simultaneously.)

If I have a real object (telephone, car), then I have an instance of the object (it has been instantiated). This means that although there are these two classes of objects (here, two children of the objects vehicle and communication devices), these are just the blueprints: you have to do something (instantiate) to actually possess a real Honda so that you can talk on your very own Nokia.

Concepts and Nomenclature: An object is a self-contained unit of code with attributes and operations. An attribute is a property or variable of the object. An operation is a method, action, or function that the object performs. An object is encapsulated; you can only use its available code (attributes and operations) through the interface of the object (the place or means whereby you pass and receive information from the object).

Polymorphism: This (page 159) means that different objects can perform similar functions, I guess. That's a bit too abstract to claim obvious importance, no?

Inheritance: You are familiar with this because HTML and CSS have inheritance. HTML elements inherit attributes from surrounding (containing) elements; if I set a font attribute for <body>, all tags contained in body inherit that same font attribute, unless the element itself contains an attribute that is different (or is made to differ through CSS)); in this parent : child relation, the child inherits properties from the parent. Similarly, objects can be grouped into larger objects (cars and bicycles are grouped into wheeled vehicles), inheriting properties from the larger object (steering mechanism, power source, brakes). The advantage is that you can set common attributes for the larger class, so that you don't have to set the same attributes for many smaller classes.

PHP Classes

Creating a PHP Class: A class is a blueprint for an object. You create a PHP class with a class keyword, as
class my_class
{
code
}

You create attributes by declaring variables within the class, and operations by declaring functions within the class.

Constructors: A PHP constructor is one kind of PHP class operation. It is created as a function, with the name (and only this name) __construct (two underlines), as
class my_class
{
  function __construct($param)
  {
    code for constructor
  }
}

You can free the space in memory used by a class through use of a destructor (not further described in text).

Instantiating: As described above, consider PHP classes as blueprints for an object. To actually use the object, you have to make your own version (not just any car: my car), a process called instantiating (not to be confused with financing). This is done by assigning the instance to a variable (a handle on the object), using the keyword new with the name of the class, and passing any required parameters. For example, to instantiate a virtual rental car, you might use $my_wreck = new rental_car('blue', 'sportster', 'cheap');.

Using Attributes: There may be advantages to having objects return values that have been created in special ways; for instance, you may want a value that is time-related (always changing), one that comes from a database (changing because of real-world inputs to the database), or one that is checked for "reality" (numbers within preset bounds, etc.). The conditioning of values can be done within classes.

Conditioned attributes are accessed through pointers; within a class, the special pointer $this-> is used when you are setting or retrieving the value of an attribute. To avoid changing the attribute within the class (which would violate a goal of keeping the insides of the object encapsulated, or free from outside influence), use __get and __set (again, two underlines) functions. They are set up like this (page 163)
class myclass
{
   var $attribute;
   function __get($name)
  {
    return $this->$name;
   }
  function __ set ($name, $value)
  {
    $this->name = $value;
   }
}

Once you have instantiated a new object ($my_wreck = new rental_car) you can use __get() and __set() to check and set values of attributes, as $my_wreck->$price = 'cheap' or $color = $my_wreck->rental_car_color;.

Seems like a lot to go through just to use some attributes in a class, but remember that if you are using this class to create objects in lots of places (stock market quotes anyone?), you change the properties within the class, meaning that all your myriad references to your class attributes all depend on only one change in one code block.

Private and Public Access to Class Attributes and Methods: Thre are three levels of access to class attributes and methods:

  1. public (default)—can be accessed from inside or outside the class
  2. private—access only from inside the class
  3. protected—halfway between public and private (see inheritance, below).
You attach the access modifiers by placing them before any functions or variables that are created within the class (example page 165).

Calling Class Operations (Methods): Once you have created a function (=method, = operation) inside a class, e.g., function my_method in class my_class, you can use the method. First, assign an instance of the class, as $my_class_handle = new my_class;, and then use the method as $my_class_handle->my_method();. If the operation returns a value, assign it as $a_myvalue = $my_class_handle->my_method(params);.

Inheritance

Implementing Inheritance: Classes can inherit to subclasses. The subclass uses the keyword extends, as class B extends A. Any attributes or operations originally available under class A are now also available under class B. B may have its own attributes and operations, but these will not be inherited upward to A.

Inheritance can be restricted through use of private and protected. If you specify private, attributes or methods will not be inherited. If you specify protected, it will not be visible outside of the class, but it will be inherited.

You can override an inherited attribute or operation by redeclaring it in a subclass. The use of the attributed or operation by the subclass will produce a different result from the use by the superclass. Overriding does not affect the attribute or operation of the superclass (pages 158-170). You can prevent inheritance of an operationg by using the keyword final in front of any function declaration in a class.

PHP does not support multiple inheritance (page 171; see note on interfaces, page 171-172).

Designing Classes

The extended example of a custom class, pages 172-181, illustrates not only classes themselves, but also means to attain some nice site goals. Note especially the intended flexibility (list page 173) to 1) alter page elements in only one page, 2) have default content for most parts of the page, with the ability to alter it or to set custom values such as title or headings 3) recognizing which page is being viewed and altering navigation accordingly (taking away the "home" link when you are on the "home" page, without having to use a unique navigation on each page!), and 4) flexibility with individual standard elements (navigation, footers) on each page. Nice goals, eh?!

In the extended example, the goal is to build a flexible html page structure, content to be filled in later. The text has the individual steps, but note the overall themes that are covered:

Listing 6.1, pages 175-178 puts this all together into the class Page() (! time to download code from the CD or class Common folder !).

Navigation Button Trick! Note the operation IsURLCurrentPage(), (page 177, described pages 178-179), which parces the session variable list to see whether a link URL is contained in the current server list of superglobals, returning a boolean which you can then use to set a CSS class. You might, for example set a CSS rule for a.current:link, a.current:hover{color:gray;} which would dull out the navigation link for the current page (or, alternatively paint it orange to highlight which page you are on).

Using require() to force the class Page() onto every html page provides a common template and quick site uniformity between pages: this is potentially very dull (a URI template type site). Listing 6.2 begins the process of carving out unique pages, amending core content. Listing 6.3 goes the next essential state, illustrating how inheritance and overrids can be used to make further alterations to, for instance, a second navigation bar. Note the initial syntax
<?php
require ('page.inc');

class ServicesPage extends Page
{...

which uses extends to provide inheritance from Page().

Advanced and New Object-Oriented Functionality in PHP -or- Why You Can't Go Back to PHP4!

Per-Class Constants: Usually, you need to instantiate a class to use its attributes. In PHP5, you can now reference a class-declared constant using a :: operator. Here's the example (page 182):
<?php
class Math {
   const pi = 3.14159;
}
echo 'Math::pi = '.Math::pi,"\n";
?>

Static Methods: The keyword static similarly allows methods to be called without instantiating the class that contains the method. Add a static function to class my_class(as static function my_function($x)) and use it as echo my_class::my_function($passed_variable_y);.

Class Type and Type Hinting: The keyword instanceof is used in an expression to create a boolean, as ($a instanceof A), which checks whether object a is an instance of class A. Type hinting (page 183) allows you to specify the type for any parameters that are passed to a function, meaning the class that contains the parameter. Syntax is function my_function (my_parameter $my_class), which forces my_parameter to be an instance of my_class (or a class that inherits down to my_class).