
Originally Posted by
Selkirk
I think the things that are unique to objects both fall under the category of eliminating duplicate code. These are inheritance and polymorphism.
Although you introduce al little overhead, you can implement inheritance and polymorphism in procedural languages by just manually implementing and maintaining a vtable, if you're willing to spend some time on it you might even implement data encapsulation and multiple inheritance (no one will know why
).
A trivial example of that in PHP:
PHP Code:
function call($object, $function, $arguments = null)
{
if($arguments == null) $arguments = array();
if(isset($object['___vtable'][$function])) // virtual call
return call_user_func_array($object['___vtable'][$function] . '_' . $function, array($object) + $arguments);
else
trigger_error('Undefined method ' . $object['___vtable'][$function] . '_' . $function);
}
function create($class, $parent = null, $virtuals = null)
{
// build virtual table and inherit
$object = array('___class' => $class);
$vtable = array();
foreach($virtuals as $name)
{
if(function_exists($class . '_' . $name))
$vtable[$name] = $class;
else if($parent != null)
if(function_exists($parent . '_' . $name))
$vtable[$name] = $parent;
}
$object['___vtable'] = $vtable;
// call constructor
if(function_exists($class . '_initialize'))
${$class . '_initialize'}($object);
return $object;
}
function House_openDoors($this)
{
echo "Opening house doors";
}
function Villa_openDoors($this)
{
echo "Opening villa doors";
}
function Vill_poolLights($this, $state)
{
echo "Pool lights are ", ($state ? 'on' : 'off');
}
$house = create('House', '', array('openDoors'));
$villa = create('Villa', 'House', array('openDoors'));
// use dynamic dispatch
call($house, 'openDoors');
call($villa, 'openDoors');
Villa_poolLights($villa, true);
Take a look at it and compare it to:
Code C++:
class House
{
public:
virtual void openDoors()
{
std::cout << "Opening house doors";
}
};
class Villa : public House
{
public:
virtual void openDoors()
{
std::cout << "Opening villa doors";
}
void poolLights(bool a_State)
{
std::cout << "Pool lights are " << (a_State ? "on" : "off");
}
};
House *l_House = new House();
Villa *l_Vill = new Villa();
l_House->openDoors();
l_Villa->openDoors();
l_Villa->poolLights(true);
Do you spot a difference?
Bookmarks