PHP static method call with namespace in member variable

Is it possible to do something like this in php? I want to have a namespace in a member variable and always be able to call every static method of this class, as I do below.

Of course, my code does not work, but I'm just wondering if this is possible at all, and that I am close to a solution, or if it is completely excluded and should always use the syntax:

\Stripe\Stripe::setApiKey(..); 

Similar question for clarification

NOTE: I cannot modify the Stripe class, it is important that it remains intact when future developers need to update the Stripe API

Simplified code:

 class StripeLib { var $stripe; public function __construct() { // Put the namespace in a member variable $this->stripe = '\\'.Stripe.'\\'.Stripe; } } $s = new StripeLib(); // Call the static setApiKey method of the Stripe class in the Stripe namespace $s->stripe::setApiKey(STRIPE_PRIVATE_KEY); 
+5
source share
2 answers

Yes, something like this is possible. There is a static class method that can be called that returns the path of the class namespace.

 <?php namespace Stripe; Class Stripe { public static function setApiKey($key){ return $key; } } class StripeLib { public $stripe; public function __construct() { // Put the namespace in a member variable $this->stripe = '\\'.Stripe::class; } } $s = (new StripeLib())->stripe; // Call the static setApiKey method of the Stripe class in the Stripe namespace echo $s::setApiKey("testKey"); //Returns testkey 
+1
source

I just tested it, yes you can do it in php.

But I think you are violating the principle of Injection Dependency here. The correct way to do this is:

 class StripeLib { var $stripe; // make sure Stripe implements SomeInterface public function __construct(SomeInterface $stripe) { // Stripe/Stripe instance $this->stripe = $stripe; } } 
0
source

Source: https://habr.com/ru/post/1245463/


All Articles