Friday, November 13, 2009

Overriding Methods








Overriding Methods


What if you're deriving a new class from a base class and happen to create a method in the new class with the same name as a method in the base class? In that case, you override the base class's method, and objects of the new class use the new method instead of the base class's method.


For example, here's the set_name method in the Animal class:



function set_name($text)
{
$this->name = $text;
}


Now that we've created a new Lion class, we might decide it would be more befitting a lion's status to have its name in all capital letters. Thus, we might add a new method, also called set_name, to the Lion class, which converts the name you pass it to all capital letters using the strtoupper method:



function set_name($text)
{
$this->name = strtoupper($text);
}


Now when you call set_name using an object of the Lion class, the Lion class's version of the set_name method is called, not the base class's version. You can see that at work in phpoverride.php, Example 7-4.


Example 7-4. Overriding methods, phpoverride.php



<HTML>
<HEAD>
<TITLE>
Overriding methods
</TITLE>
</HEAD>

<BODY>
<CENTER>
<H1>
Overriding methods
</H1>
<?php
class animal
{
var $name;

function set_name($text)
{
$this->name = $text;
}
function get_name()
{
return $this->name;
}
}
class Lion extends Animal
{
var $name;

function roar()
{
echo $this->name, " is roaring!<BR>";
}

function set_name($text)
{
$this->name = strtoupper($text);
}
}

echo "Creating your new lion...<BR>";
$lion = new Lion;
$lion->set_name("Leo");
$lion->roar();
?>
</CENTER>
</BODY>
</HTML>



The results appear in Figure 7-4note that the overridden version of the method was indeed executed.


Figure 7-4. Overriding methods.

[View full size image]









    No comments:

    Post a Comment