T
T
the5x2020-10-27 12:03:45
PHP
the5x, 2020-10-27 12:03:45

A method that returns the interface type. How does it even work?

In the example below, the makeInterviewer(): Interviewer method returns the Interviewer interface type. Next, we can access askQuestions from another method. Can you please explain how this magic works?

interface Interviewer {
    public function askQuestions();
}

abstract class HiringManager {
    abstract public function makeInterviewer(): Interviewer;

    public function takeInterview() {
        $interviewer = $this->makeInterviewer();
        $interviewer->askQuestions();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-10-27
@the5x

In the example below, the makeInterviewer(): Interviewer method returns the Interviewer interface type.
This method does not return anything, but only declares the requirements for successors - they must implement this abstract method and already return a concrete object that implements the Interviewer interface.
Accordingly, there is no magic here, it's just that in your example there are not enough descendant classes with a specific implementation.
interface Interviewer {
    public function askQuestions();
}

abstract class HiringManager {
    abstract public function makeInterviewer(): Interviewer;

    public function takeInterview() {
        $interviewer = $this->makeInterviewer();
        $interviewer->askQuestions();
    }
}

class TeamLead implements Interviewer {
  public function askQuestions() {
    ...
  }
}

class Boss extends HiringManager {
  public function makeInterviewer(): Interviewer {
    return new TeamLead();
  }
}

https://www.php.net/manual/en/language.oop5.abstra...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question