CHAPTER 2 ■ STATIC VARIABLES, MEMBERS, AND METHODS^15
New Functionality
Standard Functionality
Static members can also belong to parent classes specifically. If you were to declare a member
both in MyObject and MyOtherObject, you could also use parent:: to access the parent variable
from the child class. In this case, both the parent and child classes maintain separate values for
the static member. Listing 2-5 demonstrates how to override a static variable in a parent class
and what effect it will have on program execution.
Listing 2-5. Overriding Static Variables
class MyObject {
public static $myStaticVar=0;
function myMethod() {
self::$myStaticVar += 2;
echo self::$myStaticVar. "\n";
}
}
class MyOtherObject extends MyObject {
public static $myStaticVar=0; //Override myStaticVar
function myOtherMethod() {
echo parent::$myStaticVar. "\n";
echo self::$myStaticVar. "\n";
}
}
$instance1 = new MyObject();
$instance1->myMethod();
$instance2 = new MyObject();
$instance2->myMethod();
$instance3 = new MyOtherObject();
$instance3->myOtherMethod();
Executing Listing 2-5 produces the following results:
2
4
4
0
McArthur_819-9C02.fm Page 15 Friday, February 1, 2008 10:23 AM