【问题标题】:The conversion of methods of the class in __call()__call()中类的方法转换
【发布时间】:2020-07-08 16:19:31
【问题描述】:

有一个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);
    }
}

【问题讨论】:

  • 魔术_call 解决方案将花费您能够对返回的对象进行类型提示,并失去use 语句的编译时优势。这些在运行时不起作用,因此如果您的任何类位于不同的命名空间中,则需要使用字符串操作来处理它。如果这些不适用,那么下面的答案就可以了。

标签: php oop


【解决方案1】:

小例子:

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);
    }
}

【讨论】:

  • 如果他们想让方法名保持小写,你可以在实例化类时添加ucfirst($methodName)
  • 我知道,但目的是什么?
  • 只是在输入相同的内容 - 添加 @MagnusEriksson 建议的 ucfirst()!class_exists($class) 以检查该类是否存在。
  • 它可以简单到方法名通常以小写开头,而类名往往以大写开头。这是目前最常见的约定。他们原来的班级就是这样。
  • 如果您在 nix 系统上使用自动加载器(例如通过 Composer 的 PSR-4),那么大小写非常重要。
猜你喜欢
  • 1970-01-01
  • 2013-12-17
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多