A
A
Alexander Silaev2019-12-10 00:25:42
PHP
Alexander Silaev, 2019-12-10 00:25:42

How to guarantee the existence of a method in the heir without binding to arguments?

There is a base class MyBase. My goal is to ensure that myMethod is declared in every descendant, but I need freedom in declaring the arguments.
Those. i need something like the following

abstract class MyBase
{
    abstract public function myMethod();
}

class Foo extends MyBase
{

    public function myMethod(string $s)
    {
        //
    }
}

But, for obvious reasons, I can't do it this way.
I can solve the problem by removing the abstract method myMethod in the MyBase class altogether. But in this way I only get around the problem, not solve it.
Can it be done "correctly"? Or is this approach generally incorrect and should it be done differently?
Specific example: a class for a certain task (for example, to get data from a database, convert some data, etc.), which has a run method; the base class implements internal processes (for example, logging to the database, outputting information to the console, launching hooks, etc.) and launching the run method; each specific task can take arguments for its execution => I want to take arguments in the run method with type checking.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2019-12-10
@allsilaevex

There are no method overloads in PHP. It is better to think over the architecture correctly so that the set of arguments is stable at the level of the abstract class / interface than to pass a variable number of arguments to the method and then look for the causes of bugs and a reason for refactoring. Also, a variable number of arguments makes it tempting to give the method extra powers, smearing its original purpose.
At the class constructor level, it is possible to pass classes through dependency injection for logging, outputting information to the console, then they do not need to be passed in the run method, but can be used inside the method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question