R
R
rapidum_alder2020-04-29 16:52:02
PHP
rapidum_alder, 2020-04-29 16:52:02

Is it possible to optimize the function call by name?

I have a piece from a class.
I want that with a different value of $type, the corresponding function would be called for me.
I replaced the original CASE with such a construction, but now the question is, can the call be made even simpler? (in one line)

public function getData($id, $type){
        $functionName = 'get' . $type . 'Data';
        return $this->$functionName($id);
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-04-29
@rapidum_alder

public function getData($id, $type){
        return $this->{'get' . $type . 'Data'}($id);
    }

// или, понятно дело

// ...
$this->{'get' . $type . 'Data'}($id)
// ...

really don't know why...

I
Ilya, 2020-04-29
@rpsv

The fact that you make a call in 1 line does not mean that it will become easier. Now everything is readable and understandable. In general, a factory method would be used for such purposes, but we are talking about a dynamic language, so in the furnace)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question