有一个Api Client类指定返回特定类的方法。方法名称与被调用的类的名称相同。问题:有什么办法可以简化这个过程吗?我知道魔术方法__call(),但我不明白是否可以通过它实现同样的事情?还是会更糟?class ApiClient{ private RequestController $controller; public function __construct(string $region) { $this->controller = new RequestController($region); } public function user(): User { return new User($this->controller); } public function rating(): Rating { return new Rating($this->controller); } public function weapon(): Weapon { return new Weapon($this->controller); } public function achievement(): Achievement { return new Achievement($this->controller); }}
1 回答
婷婷同学_
TA贡献1844条经验 获得超8个赞
最小的例子:
class ApiClient
{
private RequestController $controller;
public function __construct(string $region)
{
$this->controller = new RequestController($region);
}
public function __call($methodName, $arguments)
{
// I'm skipping checks that class exists or anything else
// Also cause class names are case INsensitive you can just:
return new $methodName($this->controller);
// Or if case-sensitivity matters
$methodName = ucfirst($methodName);
return new $methodName($this->controller);
}
}
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报
0/150
提交
取消