A
A
Alexander Vertelo2020-10-31 12:44:03
PHP
Alexander Vertelo, 2020-10-31 12:44:03

Is it possible to adjust the operation of the method depending on the object?

(Sh) Coding a simple thing that should show/delete/edit/create records in the database.
There are two tables, similar in structure, but in the internal logic they are responsible for different things: one is for positions, the second is for categories.
So, I realized that the class code that works with positions is almost 100% identical to the class code for categories, except, perhaps, FROM in SQL queries and the amount of data to be updated / inserted. That is, the code can be halved, rather than copying the same thing from class to class.

What would you like to see:

class Класс() {
  function Метод($объект) {
    if($объект = объект1) :
      инструкции, если метод был вызван объектом1
    elseif($объект = объект2) :
      инструкции, если метод был вызван объектом2
    else :
      инструкции, если метод был вызван любым иным объектом
    endif;
  }
}

$объект1 = new Класс();
$объект2 = new Класс();
$объект3 = new Класс();


I hope I explained clearly.
To what extent is this possible and, importantly, reasonable?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2020-10-31
@FanatPHP

In fact, adjusting a method depending on the class is called inheritance .
But judging by the description of the problem, it is solved by stupidly building the name of the table as a property of the class.

P
pLavrenov, 2020-10-31
@pLavrenov

According to the mind, you need to read about the Adapter pattern.
But if I understand correctly, then the current task is solved by checking through is_a ()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question