【问题标题】:How do I type-hint __call() magic method in PHP?如何在 PHP 中键入提示 __call() 魔术方法?
【发布时间】:2019-12-04 01:04:19
【问题描述】:

我正在实现一个Adapter pattern 用于测试目的,我想用两个不同类的方法输入提示适配器的返回,我该如何实现?

class Foo {
  public function somethingOnlyFooHave() {};
}

class Adapter {
  protected $handler;

  public function __construct(object $handler) {
    $this->handler = $handler;
  }

  public function __call($name, ...$args) {
    $this->handler->$name($args);
  }

  public function somethingOnlyTheAdapterHave() {}
}

$foo = new Adapter(new Foo);

// How can I get type-hinting for both the Adapter and Foo?
$foo->somethingOnlyFooHave();
$foo->somethingOnlyTheAdapterHave();

【问题讨论】:

    标签: php type-hinting method-call


    【解决方案1】:

    似乎 PHP 本身无法做到这一点,但如果您使用的是 PHPStorm 2018.3+,则可以使用联合类型(或交集类型),只要它不在 __construct 上:

    class Foo {
        public function somethingOnlyFooHave() {}
    }
    
    class Adapter {
        protected $handler;
    
        public function __construct(object $handler) {
            $this->handler = $handler;
        }
    
        public function __call($name, ...$args) {
            $this->handler->$name($args);
        }
    
        /**
         * @return Adapter|Foo
         */
        public function get() {
            return $this;
        }
    
        public function somethingOnlyAdapterHave() {}
    }
    
    $foo_adapter = ( new Adapter(new Foo) )->get();
    
    // The following methods receives type-hinting:
    $foo_adapter->somethingOnlyFooHave();
    $foo_adapter->somethingOnlyAdapterHave();
    

    有用的链接:

    【讨论】:

    • 您的问题根本没有提到 PHPStorm,所以不确定有人会如何从中得出这个解决方案。
    • @NigelRen 如果你有另一个不使用 PHPStorm 的解决方案,我很想听听......
    • 因为据我所知,PHP 本身无法做到这一点。
    • @lufc 是的,您可以在写问题时添加答案。我这样做是因为我在 Stackoverflow 上找不到这些信息,并且想分享我经过大量调查后得出的解决方案。
    • @lufc 请求删除 Stackoverflow 员工的边问边答功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2013-12-17
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多