Does Php support method overloading

2019-04-29 17:41发布

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.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-04-29 18:16

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"
查看更多
淡お忘
3楼-- · 2019-04-29 18:21

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.

查看更多
男人必须洒脱
4楼-- · 2019-04-29 18:27

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.
查看更多
登录 后发表回答