Example: Object Hierarchy
define core behavior that all classes in our hierarchy should implement. We will call this top-level class
Object. I realize the creativity is somewhat lacking. We have identified 2 core behaviors that we
would like to define in our abstract class: (1) returning a string representation of an object, and
(2) comparing an instance of one object to that of another object. Here is a look at our abstract class.
<?php
class Object
{
function Object()
{
// Enforce abstract behavior.
if ( !is_subclass_of($this, "Object") ) {
trigger_error("Object instantiation from non subclass.", E_USER_ERROR);
return NULL;
}
}
function toString() {}
function equals($object)
{
return ($this === $object);
}
}
?>
a look at this example in action. Imagine we are designing a human resources application. One obvious class
in our model would be an Employee class. For the OO purists, you could model a Person and
let each person wear an Employee hat through composition, but we’ll save that for another discussion.
Let’s take a look at our Employee class.
<?php
class Employee extends Object
{
// Member variables.
var $_id;
var $_ssn;
var $_firstName;
var $_lastName;
function Employee($id, $ssn, $firstName, $lastName)
{
// Assign member variables.
$this->_id = $id;
$this->_ssn = $ssn;
$this->_firstName = $firstName;
$this->_lastName = $lastName;
}
function toString()
{
$info = "ID: ".$this->_id."n";
$info .= "SSN: ".$this->_ssn."n";
$info .= "FirstName: ".$this->_firstName."n";
$info .= "LastName: ".$this->_lastName."n";
return $info;
}
}
?>
for the equals() method was provided, since the Object class provides a sufficient one. However,
if the implementation did not suffice, we could have provided our own version of equality checking. As we further
design our object hierarchy based on Object, we know that all our classes will have 2 common behaviors:
equals() and toString().