PHP static method call with namespace in member variable


Keywords:php 


Question: 

is it possible to do something like this in php? I want to have a namespace in a member variable and just always be able to call every static method of that class like I'm doing below.

Of course my code doesn't work, but I'm just wondering if that is possible at all and that I'm close to a solution, or if that's completely out of the question and must always use the syntax:

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

Similar question for clarifications

NOTE: I cannot modify the Stripe class, it's important it stays untouched for when future devs must 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);

2 Answers: 

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

<?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


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

But I think you violate Dependency Injection principle here. The right way to do that is:

class StripeLib
{
    var $stripe;

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