Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
11

■ ■ ■


CHAPTER 2


Static Variables, Members,


and Methods


This chapter discusses the static keyword as it is applied to variables, classes, and methods.
You will learn about the scope resolution operator (::) and its implication in object-oriented
design. Finally, I will touch on the often heated debate about the usage of static classes in appli-
cation design.
To get the most from this chapter, you should already be familiar with variable scope; that
is, you should understand global, function, and class scope, and the use of the $this variable
within classes.

Static Variables
A static variable is a variable that exists only in function scope, but that does not lose its value
when the function is finished executing; that is, it remembers its value the next time the function is
called.
To declare a variable as static, you simply prefix the variable with the static keyword, as
shown in Listing 2-1.

Listing 2-1. Declaring a Basic Static Variable

function testing() {
static $a = 1;
$a *= 2;
echo $a. "\n";
}

testing();
testing();
testing();

Executing Listing 2-1 produces the following output:

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

Free download pdf