Php是否支持方法重载

use*_*074 5 php overloading

php支持方法重载.在尝试下面的代码时,它建议它支持方法重载.任何意见

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');
Run Code Online (Sandbox Code Playgroud)

因为我有重载方法,它输出为"hello world".上面的代码片段表明php支持方法重载.所以我的问题是php支持方法重载.

ily*_*oli 10

您应该在方法重写(您的示例)和方法重载之间做出区别

这是一个简单的例子,说明如何使用__call魔术方法在PHP中实现方法重载:

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"
Run Code Online (Sandbox Code Playgroud)