【问题标题】:Static methods with __construct带有 __construct 的静态方法
【发布时间】:2016-10-09 09:33:34
【问题描述】:

我需要使用带有__construct() 方法的静态方法来实例化Client 对象,但据我所知,没有办法使用__construct(),因为使用静态方法时对象没有被实例化。

我认为我可以使用 init 方法。

class API
{

    static $client;

    public static function init()
    {
        $settings = [
            'username' => 'user1',
        ];

        self::$client = new Client($settings);
    } 

    public static function foo( )
    {
        self::$client->action('Foo text');
    }

}

API::init();

然后我可以在其他地方加载上面的类,然后做下面的事情。

API::foo();

我的问题:

  1. 我写课程的方式有什么问题吗?
  2. 以上代码是否会导致性能问题?
  3. 有没有更好的办法?

感谢任何帮助。

【问题讨论】:

    标签: php class oop constructor static-methods


    【解决方案1】:

    作为一种方法,这种方法很好,但在这里更多的是SOLID,我会在init() 函数中传递Client,比如init(Client $client),而不是在课堂上直接实例化它。 $settings 也是如此,最好作为参数传递或保存在一些 private 变量中,而不是在初始化程序中硬编码。

    DL字母,Dependency Inversion PrincipleLiskov Substitution Principle

    没有性能问题,而只是一种架构方法。但就我而言,我在这里没有看到任何避免构造函数并使用$api = new API($client, $settings); 而不是静态调用的先决条件。

    构造函数(或初始化器)签名看起来像

    public function __construct(Client $client, array $settings);
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 2016-04-05
      相关资源
      最近更新 更多