Does Php support method overloading

2019-04-29 18:08发布

问题:

Does php support method overloading. While trying below code it suggests it supports method overloading. Any views

class test
{
  public test($data1)
  {
     echo $data1;
  }
}

class test1 extends test
{
    public test($data1,$data2)
    {
       echo $data1.' '.$data2;
    }
}

$obj = new test1();
$obj->test('hello','world');

As i have overload the method it gives the output as "hello world". Above code snippet suggests php supports method overloading. So my question is does php support method overloading.

回答1:

You should make the difference between method overriding (your example) and method overloading

Here is a simple example how to implement method overloading in PHP using __call magic method:

class test{
    public function __call($name, $arguments)
    {
        if ($name === 'test'){
            if(count($arguments) === 1 ){
                return $this->test1($arguments[0]);
            }
            if(count($arguments) === 2){
                return $this->test2($arguments[0], $arguments[1]);
            }
        }
    }

    private function test1($data1)
    {
       echo $data1;
    }

    private function test2($data1,$data2)
    {
       echo $data1.' '.$data2;
    }
}

$test = new test();
$test->test('one argument'); //echoes "one argument"
$test->test('two','arguments'); //echoes "two arguments"


回答2:

So my question is does php support method overloading(?).

Yes, but not in that way, and, in your example, it not suggests that this kind of overloading is correct, at least with the version 5.5.3 of it and error_reporting(E_ALL).

In that version, when you try to run this code, it gives you the following messages:

Strict Standards: Declaration of test1::test() should be compatible
with test::test($data1) in /opt/lampp/htdocs/teste/index.php on line 16

Warning: Missing argument 1 for test::test(), called in /opt/lampp/htdocs/teste/index.php 
on line 18 and defined in /opt/lampp/htdocs/teste/index.php on line 4

Notice: Undefined variable: data1 in /opt/lampp/htdocs/teste/index.php on line 6
hello world //it works, but the messages above suggests that it's wrong.


回答3:

You forgot to add 'function' before test in both cases. Method is called of child class because when you call a method from child class object it first check if that method exist in child class, if not then it look into inherited parent class with visibility public or protected check and if method is exist than return the result according to that.