Search code examples
phpoopinterfacetype-hinting

Type Hinting For Multiple Unrelated Interfaces


Is there a way in php to type hint for two different, unrelated interfaces? For example:

interface errorable {
   function error($msg);
}

interface recordable {
   ssh_for_recorder();
}

class uploader__module extends base__module implements errorable, recordable {
   public function ssh_for_recorder() {
      return new ssh2;
   }
   public function error($msg) {
      $this->errors[] = $msg;
   }

   public function upload() {
      $recorder = new recorder($this);
      $recorder->run();
   }
}

class recorder {
   private $ssh2;
   private $module;
   private function upload() {
      if (!$this->ssh2) {
         $this->module->error("No SSH2 connection");
      }
   }
   public function __construct({recordable,errorable} $module) {
      $this->module = $module;
      $this->ssh2 = $module->ssh_for_recorder();
   }
}

As you can see in the above code, the recorder class expects its module to have the ability to run both error() and ssh_for_recorder(), but these are defined by different interfaces. errorable need not be recordable and vice versa either.

Is there a best practice for doing this? I was thinking of creating an interface that extends from recordable and errorable and having upload__module implement that, but I don't know what to call it.


Solution

  • No, this is not possible in php.

    There are other languages (mostly functional) that support this feature which is called a union type ( http://en.wikipedia.org/wiki/Sum_type ).