本文介绍了Php 是否支持方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

php 是否支持方法重载.在尝试下面的代码时,它表明它支持方法重载.任何意见

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');

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

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.

推荐答案

你应该区分方法覆盖(您的示例)和 方法重载

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

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

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"

这篇关于Php 是否支持方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 02:34