Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^14) CHAPTER 2 ■ STATIC VARIABLES, MEMBERS, AND METHODS
class MyOtherObject extends MyObject{
function myExtendedMethod() {
echo "myExtendedMethod is declared in MyOtherObject\n";
self::myBaseMethod();
}
}
MyOtherObject::myExtendedMethod();
Executing Listing 2-3 produces the following output:
myExtendedMethod is declared in MyOtherObject
I am declared in MyObject
In an extended class, you may want to call a method that is defined in the base class but
that is then overridden. For example, you might do this when you want to extend a class to add
extra functionality to an existing method. To achieve this, you use the parent scope, as demon-
strated in Listing 2-4.
Listing 2-4. Using parent Scope
class MyObject {
function myMethod() {
//Standard functionality
echo "Standard Functionality\n";
}
}
class MyOtherObject extends MyObject{
function myMethod() {
//Add some new functionality
echo "New Functionality\n";
//Then call the original myMethod that is defined in MyObject
parent::myMethod();
}
}
$obj = new MyOtherObject();
$obj->myMethod();
Executing Listing 2-4 from the command line produces the following output:
McArthur_819-9C02.fm Page 14 Friday, February 1, 2008 10:23 AM

Free download pdf