Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP static method call with namespace in member variable

Tags:

namespaces

php

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);
like image 838
NaturalBornCamper Avatar asked Nov 08 '22 18:11

NaturalBornCamper


1 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
like image 70
Daan Avatar answered Nov 14 '22 21:11

Daan