Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^12) CHAPTER 2 ■ STATIC VARIABLES, MEMBERS, AND METHODS


2

4

8

In this example, the testing() function stores the value of $a internally after each execu-
tion. The next time the testing() function is called, the old value of $a is restored, multiplied
by 2, and echoed anew.
Notice that variable’s default value is initialized to 1. This assignment will occur only the
first time the variable is initialized. It will not be called with each execution of the function.

■Note It is illegal to default a static variable to the product of an expression. An expression is anything that
is not a value itself. For example, (1+1), $variable, and anyfunc() are examples of expressions.

You are probably thinking that this doesn’t seem particularly useful, as you could just as
easily use a global variable to achieve the same result. However, global variables are accessible
by all functions, and as such, can cause conflicts if two or more functions use a similarly named
variable that is designed to be independent. Also, using a static variable doesn’t require any
more syntax space than importing a global variable, so when only one function needs to access
the variable, using a static variable instead of a global variable is preferred.

Static Usage in Classes
The static keyword is used in classes in two key ways: for static members and static methods.
Within classes, you can use the scope resolution operator to access different scope levels.

Static Members


A static member is a class variable that is best thought of as belonging to the class and not any
specific instance of a class. Unlike a normal instance variable, a static member retains only one
value for all instances; that is, all instances share the one member. Listing 2-2 demonstrates the
declaration and access of a static member.

Listing 2-2. Declaring a Static Member

class MyObject {

public static $myStaticVar=0;

function myMethod() {
self::$myStaticVar += 2;
echo self::$myStaticVar. "\n";
}

McArthur_819-9C02.fm Page 12 Friday, February 1, 2008 10:23 AM

Free download pdf