简体   繁体   中英

Static methods with __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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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