发送接口到构造函数PHP

时间:2017-11-08 08:33:32

标签: php interface construct

我已经下载了付款连接的示例。不,我正在尝试使用它,但构造函数希望在我声明 ClassName 时获取界面 但我不知道该怎么做。我试过了

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

还有更多,但我无法弄明白。我所知道的只是实现一个类的接口。也许是一个noob问题,但我几乎一天都没有成功搜索过。

$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;
    }
}

1 个答案:

答案 0 :(得分:2)

你应该在这些方面寻找解决方案

// 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);