You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何调用参数为接口类型的类execute方法

解决方法

要正确调用execute()方法,你需要先创建一个实现了RequestInterface接口的类,再将该类的实例作为参数传入即可,具体操作步骤如下:

1. 实现RequestInterface接口

定义一个类实现RequestInterface,完成接口要求的getMethod()和getPath()两个方法的逻辑:

class CustomRequest implements RequestInterface
{
    // 用于存储请求方法和请求路径的属性
    private string $method;
    private string $path;

    public function __construct(string $method, string $path)
    {
        $this->method = $method;
        $this->path = $path;
    }

    // 实现接口要求的getMethod方法,返回请求方法
    public function getMethod(): string
    {
        return $this->method;
    }

    // 实现接口要求的getPath方法,返回请求路径
    public function getPath(): string
    {
        return $this->path;
    }
}

2. 调用execute方法

实例化你写的实现类,把实例作为参数传给execute()即可:

$client = new Client();
// 按需传入你需要的请求方法和路径,示例为POST请求 /api/create
$request = new CustomRequest('POST', '/api/create');
$client->execute($request);

补充:如果你使用的PHP框架本身已经提供了符合RequestInterface规范的实现类,可以直接实例化框架自带的类传入,无需自行实现接口。

内容的提问来源于stack exchange,提问作者Kaspar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:45:02