1

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 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.