D
D
Dmitry Larchikov2016-02-17 15:57:05
PHP
Dmitry Larchikov, 2016-02-17 15:57:05

Method overloading in PHP as in Java. Maybe?

In java, there is such a thing as method overloading. This means that we can write several methods with the same name, which will differ in the number or type of incoming data.
For example:

String getName(String fullname) {};
String getName(int id) {};
String getName(User user) {};
String getName(String firstName, String lastName) {};

Depending on what we pass as input, a method with suitable parameters will be called.
Programming in PHP, I could not do this. At least a warning pops up
Declaration of Framework\Widget\Icon::get() should be compatible with Framework\Base\Widget::get()

Googling the words overloading leads to some kind of pseudo- overloading php.net/manual/ru/language.oop5.overloading.php , which is called magic.
The question actually is whether it is possible to make, for example, an heir-class with a method whose number of parameters differs from the parent and not receive a warning. Disabling warnings is not advised :)
class A {
    public function message ($user, $message) {}
}
class A extends B {
        public function message ($user_id, $message, $type) {}
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Kubintsev, 2016-02-17
@dimka3210

No, you can’t, although such wishes, as far as I remember, were in the RFC. Perhaps it will appear in the future.

M
MNB, 2016-02-17
@MNB

getName(){
   switch(func_num_args()){
   }
}

T
ThunderCat, 2016-02-17
@ThunderCat

Let's start with the fact that there is no strong typing in puff, and there is no out-of-the-box method reloading. Crutches and bicycles - that's my answer)
BUT if the functionality is the same as you wrote in the last lines - make the parameters optional

public function message ($user_id, $message="", $type="someDefaultType") {}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question