user3631047 user3631047 - 8 months ago 50
PHP Question

Static methods with __construct

I need to use static methods with

method to instantiate the
object but the as far as I know there is no way to use the
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');



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


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