dt3674 2016-10-09 09:33
浏览 816
已采纳

使用__construct的静态方法

I need to use static methods with __construct() method to instantiate the Client object but the as far as I know there is no way to use the __construct() since the object is not instantiated when using static methods.

I thought I can use an init method.

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();

Then I can load the above class in other places and do the below.

API::foo();

My Questions:

  1. Is there anything wrong with the way I wrote the class?
  2. Does the above codes cause performance issue?
  3. Is there any better way?

Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • duanfei8399 2016-10-09 11:41
    关注

    As an approach this method is fine, but to be more SOLID here I would pass Client in init() function like init(Client $client) rather than instantiating it right in class. So do and $settings, better pass as an argument or preserve in some private variable rather than hardcoding in initializer.

    It refers to D and L letter, the Dependency Inversion Principle and Liskov Substitution Principle

    No performance issues, but only an architectural approach. But as to me I don't see any preconditions here for avoiding constructor and use $api = new API($client, $settings); rather than static invocation.

    And constructor (or initializer) signature would look like

    public function __construct(Client $client, array $settings);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器