简体   繁体   English

在PHP中使用静态方法有什么好理由?

[英]What are good reasons to use static methods in PHP?

有没有人有任何使用静态方法而不是动态的好例子?

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

当您不需要访问实例成员时。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM