【问题标题】:How do I correctly typehint an interface in PHP?如何在 PHP 中正确输入接口?
【发布时间】:2013-07-28 10:16:26
【问题描述】:

这就是我想要做的:

<?php

interface PaymentGatewayInterface {

    public function pay(array $bill);
    public function processNotification($notification);

}

class Payment {

    protected $gateway;

    public function __construct(PaymentGatewayInteface $gateway)
    {
        $this->gateway = $gateway;
    }   

    public function pay(array $bill)
    {
        return $this->gateway->pay($bill);
    }

    public function processNotification($notification)
    {
        return $this->gateway->processNotification($notification);
    }

}

class Paypal implements PaymentGatewayInterface {

    public function pay(array $bill)
    {
    }

    public function processNotification($notification)
    {
    }

}

$a = new Payment(new Paypal);

这是我从 PHP 收到的错误:

Catchable fatal error: Argument 1 passed to Payment::__construct() must be an instance of PaymentGatewayInteface, instance of Paypal given, called in /in/oP75h on line 43 and defined in /in/oP75h on line 14

这里你可以自己测试一下:http://3v4l.org/oP75h

我最初在 Laravel 4 和 Mockery (TDD) 中工作,但经过一段时间的调试后,我意识到这实际上“只是”一个 PHP 问题。

【问题讨论】:

    标签: php laravel laravel-4 type-hinting


    【解决方案1】:

    你有一个错字:-

    public function __construct(PaymentGatewayInteface $gateway)
                                                  ^ 'r' missing
    

    应该是:-

    public function __construct(PaymentGatewayInterface $gateway)
    

    您在界面中缺少“r”。

    【讨论】:

    • 再愚蠢不过了。 :) PHP 至少可以就此向我们提出建议,例如“找不到 的声明”,而不是抛出一个完美的错误消息。非常感谢。
    • 在某种程度上确实如此,只是反过来:“必须是 的实例”。
    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 2016-07-15
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2021-10-20
    • 2018-06-28
    • 1970-01-01
    相关资源
    最近更新 更多