Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are good reasons to use static methods in PHP?

Does anyone have any good examples of using static methods instead of dynamic?

like image 784
Leonardo Avatar asked Jan 13 '11 21:01

Leonardo


People also ask

Why do we use static methods in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

What are reasons for using a static method or variable?

Static variables are used to keep track of information that relates logically to an entire class, as opposed to information that varies from instance to instance.


4 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
like image 173
Stephen Avatar answered Oct 03 '22 20:10

Stephen


When you don't need access to instance members.

like image 41
ken Avatar answered Oct 03 '22 21:10

ken


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');
}
like image 30
Geoffrey Wagner Avatar answered Oct 03 '22 19:10

Geoffrey Wagner


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.

like image 29
Bailey Parker Avatar answered Oct 03 '22 19:10

Bailey Parker