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
相关产品推荐
相关产品推荐

