【问题标题】:Does Php support method overloadingphp是否支持方法重载
【发布时间】:2013-06-26 09:17:37
【问题描述】:

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

由于我重载了该方法,因此它将输出显示为“hello world”。 上面的代码 sn-p 表明 php 支持方法重载。所以我的问题是php是否支持方法重载。

【问题讨论】:

标签: php overloading


【解决方案1】:

你应该区分method overriding(你的例子)和method overloading

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

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"

【讨论】:

  • 如何让其中一个受到保护而另一个公开?似乎如果 __call 需要公开,那会敞开大门吗?用例、公共 getter、受保护的 setter 都与数据属性同名......或者您可能必须剖析调用者信息(可能有点冗长)
  • 我这里能不能有多个调用函数?
  • 请开发您所说的多个调用函数。如果超出此问题的范围,请将其作为新问题发布。我相信你会得到一个准确的答案。
【解决方案2】:

所以我的问题是 php 是否支持方法重载(?)。

是的,但不是那种方式,而且在你的例子中,它并不表明这种重载是正确的,至少在它的 5.5.3 版本和error_reporting(E_ALL) 中是正确的。

在该版本中,当您尝试运行此代码时,它会为您提供以下消息:

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】:

    在这两种情况下,您都忘记在测试之前添加“功能”。方法被称为子类,因为当您从子类对象调用方法时,它首先检查该方法是否存在于子类中,如果不存在,则它查看具有可见性的继承父类公共或受保护检查,如果方法存在则返回结果就是这样。

    【讨论】:

    • 在 PHP 中,function 关键字的使用不是必须的,在这种情况下也没有什么区别。
    猜你喜欢
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多