如何在 php 中的 class 构造函数中传递接口实例

How to pass interface instance in class constructor in php

我有以下class

class InterfaceImplementation{
    public function __construct(ServiceInterface $oService){
        $this->oService = $oService;
    }
}

当我创建 class 对象时

$obj = new InterfaceImplementation();

如何传递接口实例?这样的编码方式正确吗?

在创建新的 InterfaceImplementation 之前,您需要有一个有效的 ServiceInterface 对象。拥有服务对象后,您可以在创建时传递它 InterfaceImplementation

$service = new ServiceInterface(); // make sure its a valid object
$implementation = new InterfaceImplementation($service);

专业提示:查找依赖注入容器。它会让你的生活变得更轻松。

任何将实现 ServiceInterface 的对象都可以使用并传递给构造函数。 您必须创建 class 的实例,但在 InterfaceImplementation 中,您将使用接口 API(接口中声明的方法),而不是来自特定 class 的方法.