Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^16) CHAPTER 2 ■ STATIC VARIABLES, MEMBERS, AND METHODS
All of the prior examples use instances of classes to access methods. You may also pass a
class name to the left of the :: operator to access a member statically and avoid needing to
create an instance. This will save you writing instantiation code, and it can be more efficient, as
each instance of a class takes up a small amount of system resources. Calling a class method
statically is demonstrated in Listing 2-6.
Listing 2-6. Calling a Class Method Statically
class MyObject {
public static $myVariable = 10;
}
echo MyObject::$myVariable;
Running Listing 2-6 has the following result:


10

Note again the use of the $ symbol when accessing myVariable via the :: operator. This is
because PHP currently does not support the use of dynamic static variables—that is, variable
variables that are static. When using $this->$variable, the member that is accessed is the value
contained in $variable. Accessing a variable without the $ symbol will actually be looking for a
class constant, and constants cannot be accessed via $this.
The introduction of the static:: scope in PHP 6 allows you to stop using self:: and
parent::. When you mean to refer to the final functional class, use static::, which will perform a
computation immediately prior to code execution to determine the most descendant member.
This process is called late binding, and it allows you to override a static variable in a child class
and access the final member from a function declared in the parent, as you’ll see in the next
section.

Static Methods


Static methods follow the same rules as static variables. You mark them with the static keyword,
and you use the scope resolution operator (::) to access them via the class’s name.
Static methods have one key difference from non-static methods: you no longer need to
have an instance of the class to call your method. Listing 2-7 shows an example of using a static
method.

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

Free download pdf