O
O
Oleg2020-01-16 11:14:39
PHP
Oleg, 2020-01-16 11:14:39

Is there a common class in PHP that all classes inherit from?

Greetings. I am implementing the repository pattern and in the interface I want to add the save function, which should accept objects of different types. Proper polymorphism. Java has a generic Object type, but is there a similar one in PHP? Or do you need to make your own Object class?

interface InterfaceRepository {
  public function save($object);
}

abstract class LexiconRepository implements InterfaceRepository{
  public function save(Lexicon $object) {} //Хочу здесь принимать объекты конкретного типа, а в интерфейсе нельзя указать общий тип для всех классов 
}

class DeviceRepository implements LexiconInterface {
    public function save(Device $device)  {} //А тут уже нужен Device
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Romashkan, 2020-01-16
@afagorn

I want to accept objects of a specific type here, but in the interface you cannot specify a common type for all classes

You are violating the Liscow Substitution Principle when you require a more specific type in the descendants than in the parent, you shouldn't do that.
For instances of any classes, there is a type hint object, but it will not help you for the reason described above.
There is no point in a common interface for all repositories.

L
Lazy @BojackHorseman PHP, 2020-01-16
Tag

no

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question