Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^18) CHAPTER 2 ■ STATIC VARIABLES, MEMBERS, AND METHODS
Listing 2-8 generates the following output:
Called from MyExtendedObject
The code in Listing 2-8 will properly call myOtherMethod inside MyExtendedObject. Prior to
PHP 6, it was not possible to call the method in the extended class from the parent, and self::
would always result in a calling from MyObject.
Sometimes it is difficult to know when to use a static method versus a non-static one. One
rule of thumb is that you should use a static method any time the method does not include the
$this variable. If you don’t need an instance, you should probably use a static class instead of
unnecessarily instantiating classes. Further, you cannot use $this from within a static method,
as the method belongs to no-specific instance.
The Static Debate
The usage of static classes is a controversial subject. Some developers make it a rule to never
use the scope resolution operator on a class name. I personally feel this is extreme, and you will
find static classes used throughout all major OOP frameworks. The static debate centers around
a design principle called Inversion of Control (IoC).
IoC is a design principle that tries to get rid of all interdependence in OOP. This principle
is important in complex systems, and allows for objects to be more polymorphic and encapsu-
lated. The less interdependence, the easier it is to test a component in isolation.
The problem with static classes and IoC is that static accessors, by their very nature, define
bindings between two classes, as the name of the class is hard-coded. This means that a class
cannot be easily simulated when trying to test another class in isolation.
■Note In PHP, it is not possible to use a variable as a class name for the scope resolution operator.
$classnameinvar::somemethod() is invalid and will result in a parse error.
Just the Facts
Static variables are modified function variables that do not lose their value when a function’s
execution is complete. You create a static variable with the static keyword and may provide a
default initialization value; however, that initialization value may not be an expression. Static
variables can be useful for eliminating variable-naming conflicts that may occur when using
global variables to simulate static variables.
The static keyword can also be used in classes to modify properties and methods. When
used on a property, it changes the property from holding a value per instance to holding a
single value that is intrinsic to the class itself. This value can also be considered shared between
all instances of a class.
McArthur_819-9C02.fm Page 18 Friday, February 1, 2008 10:23 AM

Free download pdf