Does anyone have any good examples of using static methods instead of dynamic?
5 Answers
Singleton:
class SingletonClass {
private static $instance;
private function __construct() { }
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public static function init() {
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// other public, dynamic methods for singleton
}
$singleton = SingletonClass::init();
Track number of instances:
class CountMe {
public static $instances = 0;
public function __construct() {
CountMe::$instances++;
}
public function __destruct() {
CountMe::$instances--;
}
}
$a = new CountMe();
$b = new CountMe();
echo CountMe::$instances; // outputs 2

- 18,827
- 9
- 60
- 98
-
Something missing. Why did you used init() instead of __construct? Why should i call init() instead of just using the method i need and let the class create its instance in the __construct? – Shoe Jan 13 '11 at 22:09
-
Because the constructor is private. This ensures that you can't create the class yourself. You have to go through the init method, and the init method either returns a single instance, or creates one and returns it. In this way, you will always only have a single instance of the class. – Stephen Jan 13 '11 at 22:13
-
The whole purpose of a singleton is to be just that: single. This structure prevents multiple instances of an object from being created. – Bailey Parker Jan 13 '11 at 22:14
-
2In other words: You cannot do this `$var = new SingletonClass();` because an error will be thrown. But the static method can do this `self::$instance = new $c;` because it has access to the private constructor. – Stephen Jan 13 '11 at 22:15
-
Lastly, if you were given access to `__construct`, you would have to instantiate the class every time you want to get an instance of it, thus: not a singleton. – Stephen Jan 13 '11 at 22:19
A database connection would be a good use for a static function. You dont need direct access to an entire DB object, you just need access to the connection resource. So you can call
$connection = new DatabaseConnection();
StaticClass::setDatabase($connection);
$result = StaticClass::getDatabaseConnection()->query();
But if you need access to the class for storage later or multiple instances of the same object, then you would not want to go static.
Your class also now lives in a global scope, so you can access it from any class, in any scope, anywhere in your codebase.
function getUsers()
{
$users = StaticClass::getDatabaseConnection()->query('SELECT * FROM users');
}

- 818
- 1
- 5
- 11
In a less code-oriented nature, here's how I define static methods (I'll use a bank as an example): If you had a bank class and would like to open a new bank you would use:
$b = new Bank;
Now let's say you wanted to add a new employee to this bank. Simply call:
$b->addEmployee( 'Person' );
Since you are applying the action to the bank you created and not the company that owns the bank as a whole you use a member method. Now let's say the company's traded some assets and made money. To update their total money you would call this:
Bank::addToCompanyBalance( 1000000 );
Notice how since the action wasn't just being applied to the bank we created, we used a static method instead.
Granted this example is very oversimplified, but I like the analogy. In a more programmatic sense case, static members are good for:
Singletons
class Singleton
private static $instance;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if( !isset( self::$instance ) ) self::$instance = new IamOne;
return( self::$instance );
}
}
Creating classes that may fail
Ex. A file handler class may not always want to create a new object (Say the file passed doesn't exist or can't be opened).
With abstract classes
Some classes may not wish to have instances (Ex. A router that interprets a user's request). Abstract classes, however, can be called statically and therefore can use static methods.

- 15,599
- 5
- 53
- 91
-
That helped me out a lot. Sometimes it really helps to use a real-world example, like your bank, instead of showing over-technical use-cases that might not make any sense to someone unfamiliar with the concept (\*cough\* most PHP.net documentation). I've just started learning to use classes to make plugins and wanted to know why people use static vs. non-static methods and properties. – Phil Tune Apr 01 '15 at 21:56
Example: Use static methods to create instances of an object which might perhaps take different arguments.
Class DBConnection
{
public static function createFromConfiguration(Configuration $config)
{
$conn = new DBConnection();
$conn->setDsn($config->getDBDsn());
$conn->setUser($config->getDBUser());
$conn->setPassword($config->getDBPass());
return $conn;
}
public static function newConnection($dsn, $user, $password)
{
$conn = new DBConnection();
$conn->setDsn($dsn);
$conn->setUser($user);
$conn->setPassword($password);
return $conn;
}
}

- 2,344
- 3
- 34
- 41
-
I dunno if I like this implementation. Strategy Pattern would be better, I think. – Stephen Jan 13 '11 at 21:55
-
Strategy pattern encapsulates objects, this is a factory system for creating objects. It's a workaround for no support for method, in this case constructor, overloading in PHP. – SlappyTheFish Jan 13 '11 at 22:12
-
There's a better way to fake method overloading. PHP has some cool magic methods like `__call` to help. Check this out: http://www.dinke.net/blog/en/2007/08/01/method-overloading-in-php5/ – Stephen Jan 13 '11 at 22:24
-
-
@Kyle Wikipedia is a good place to start: http://en.wikipedia.org/wiki/Design_Patterns and if you want more then look at some of the classic books: http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 – SlappyTheFish Jan 14 '11 at 07:54
-