开发者

What are good reasons to use static methods in PHP?

Does anyone have any good examples of using s开发者_开发知识库tatic methods instead of dynamic?


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


When you don't need access to instance members.


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');
}


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.


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜