2

I have downloaded an example for a payment connection. No i am trying to use it, but the constructor want's to get the interface when i declare ClassName But i have no idea how to do that. I tried

$interface = CallbackInterface::class;
$interface = CallbackInterface();
$interface = CallbackInterface;

And many more , but i can't figure it out. Only thing i know is to implement an interface with a class. Maybe a noob question, but i've searched almost a day with no success.

$config = new Config('string1', 'string2');
$pay = new ClassName($config, $interface);

interface CallbackInterface
{   
    public function Key($sIdentifier, $sTransactionKey);
    public function tSuccess($sTransactionKey);
}

class ClassName
{
    public function __construct(Config $oConfig, CallbackInterface $oCallbacks)
    {
        $this->oConfig = $oConfig;
        $this->oCallbacks = $oCallbacks;
    }
}
user1664803
  • 293
  • 1
  • 7
  • 22
  • You are correct already! ;-) "Only thing i know is to implement an interface with a class". Interface are not built for instantiation. See https://stackoverflow.com/questions/8552505/when-to-use-interfaces-in-php or https://stackoverflow.com/questions/1814821/interface-or-an-abstract-class-which-one-to-use or https://stackoverflow.com/questions/20463/what-is-the-point-of-interfaces-in-php for more info – Edwin Nov 08 '17 at 08:38
  • Is the file with the interface included, what do you mean by `constructor want's to get the interface` – ArtisticPhoenix Nov 08 '17 at 08:39
  • 1
    Yes, you need to implement the interface in a class and pass an instance of that class to the constructor. That's what an interface hint means: *I expect some object which conforms to this interface.* It doesn't want *the interface*, it wants an object with that interface. – deceze Nov 08 '17 at 08:43

1 Answers1

3

you should be looking for a solution along these lines

// Create a class that implements the interface (e.g. MyClass)
// MyClass implements the interface functions: Key and tSuccess
// MyClass can now be injected as type CallbackInterface into the __construct() of class ClassName

Class MyClass implements CallbackInterface
{
    public function Key($sIdentifier, $sTransactionKey)
    {
        // your implementation here
    }
    public function tSuccess($sTransactionKey)
    {
        // your implementation here
    }
}

interface CallbackInterface
{   
    public function Key($sIdentifier, $sTransactionKey);
    public function tSuccess($sTransactionKey);
}

class ClassName
{
    public function __construct(Config $oConfig, CallbackInterface $oCallbacks)
    {
        $this->oConfig = $oConfig;
        $this->oCallbacks = $oCallbacks;
    }
}

$config = new Config('string1', 'string2');
$interface = new MyClass(); // you've now instantiated an object of type CallbackInterface
$pay = new ClassName($config, $interface);
lovelace
  • 1,195
  • 1
  • 7
  • 10