Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 2 ■ STATIC VARIABLES, MEMBERS, AND METHODS^13

}

$instance1 = new MyObject();
$instance1->myMethod();
$instance2 = new MyObject();
$instance2->myMethod();

Executing Listing 2-2 produces the following output:

2

4

This is the result because the static member variable is shared among all instances of the
class.
Notice the use of the :: scope resolution operator and the self scope instead of $this. This
is because $this refers only to the current instance of the class, whereas self:: refers to the
class itself. Let’s take a closer look at this scope resolution operator.

■Note Unlike with $this, when using static variables, you must include the $ symbol after the scope
resolution operator.

Paamayim Nekudotayim


Say what? OK, I know, paamayim nekudotayim is even hard to read. It literally means “double
colon” in Hebrew. The good news is that you can forget the name right now.
The paamayim nekudotayim symbol, also known as the scope resolution operator, is specified
by a double colon (::) and is used to access different scope levels within classes. This operator
takes a scope on the left and a member on the right.
You can use two magic scopes with the scope resolution operator: self and parent. Addi-
tionally, PHP 6 introduces static scope.
The code shown earlier in Listing 2-2 illustrates access to the self scope. This scope refers
to the current class, but unlike $this, it does not refer to a specific instance of a class. It cannot
be used outside a class and is not knowledgeable of its position in an inheritance tree. That
said, self, when declared in an extended class, can call methods declared in a base class but
will always call the overridden method. This is demonstrated in Listing 2-3.

Listing 2-3. Accessing Functions in a Parent Class with self Scope

class MyObject {

function myBaseMethod() {
echo "I am declared in MyObject\n";
}

}

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

Free download pdf