Robert Robert - 2 months ago 10
PHP Question

accessing static method within class variable

I have been looking around attempting to find out how to access a stripe static method within my own class. Essentially extending the stripe library.

Within Stripes Documentation the code would look like this:

\Stripe\Customer::create();


The code I am attempting to access from the stripe library:

public static function create($params = null, $opts = null)
{
return self::_create($params, $opts);
}


Current top of file:

use Stripe\Charge;
use Stripe\Stripe;
use Stripe\Customer;
/**
* Handles all stripe specific options
*/
class _Stripe
{
protected $charge;
protected $stripe;
protected $customer;
/**
* Init Stripe Charge
*/
public function init_charge()
{
$this->charge = new Charge;
}
/**
* Init Stripe Class
*/
public function init_stripe()
{
$this->stripe = new Stripe;
}
/**
* Init Stripe Customer
*/
public function init_customer()
{
$this->customer = new Customer;
}


So far I have this:

$this->customer = new Customer;
$this->customer::create();


which is considered invalid syntax. Is there any possible way for me to do this within my own class?

Things I have tried:

{$this->customer}::create();
Got: Unexpected '}'


Thanks in advance!

Answer

This one is possible in PHP7 ( i don't sure about other versions ):

<?php

class Test
{
    public static $var1 = "something";

    public static function charge()
    {
        return self::$var1;
    }
}

$Object = new Test();
echo $Object->charge(); // Output: something

As you updated your question, i simulated with your structure and the below code works on PHP 7.0.5-3:

<?php

namespace Stripe;

class Customer
{
    public static function create($params = null, $opts = null)
    {
        return self::_create($params, $opts);
    }

    public static function _create($params, $opts)
    {
        return 'bla bla';
    }
}

// ...
use Stripe\Customer;

$Customer = new Customer();
echo $Customer->create(null, null); // Output: bla bla

// ...

class OtherClass
{
    public $instance;

    public function run()
    {
        $this->instance = new Customer();
        echo $this->instance->create(null, null);
    }
}

(new OtherClass)->run();
Comments