You
can access a static method or property directly without creating any instance of that
class. A static member is like a global member for that class and all instances of that
class. Also, static properties persist the last state of what it was assigned, which is
. very useful in some cases.
You might ask why someone uses a static method. Well, most of the static methods
are similar to utility methods. They perform a very specific task, or return a specific
object (static properties and methods are used significantly in design patterns, we
will learn that later). So declaring a new object every time for those works might be
considered resource extensive. Let's see an example of static methods.
Consider that in our application we keep support for all three databases, MySQL,
PostgreSQL, and SQLite. Now we need to use one particular driver at a time. For
that, we are designing a DBManager class, which can instantiate any driver on
demand and return that to us.
//class.dbmanager.php
class DBManager
{
public static function getMySQLDriver()
{
//instantiate a new MySQL Driver object and return
}
public static function getPostgreSQLDriver()
{
//instantiate a new PostgreSQL Driver object and return
}
public static function getSQLiteDriver()
{
//instantiate a new MySQL Driver object and return
}
}
?>
Chapter 2
[ 37 ]
How do we use this class? You can access any static property using a :: operator
and not using the -> operator.
Pages:
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59