php 什么是php中的函数重载和覆盖?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2994758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:21:31  来源:igfitidea点击:

What is function overloading and overriding in php?

phpoverloadingoverriding

提问by Parag

In PHP, what do you mean by function overloading and function overriding. and what is the difference between both of them? couldn't figure out what is the difference between them.

在 PHP 中,函数重载和函数覆盖是什么意思。两者有什么区别?无法弄清楚它们之间有什么区别。

回答by Jacob Relkin

Overloadingis defining functions that have similar signatures, yet have different parameters. Overridingis only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to overridethat method.

重载是定义具有相似签名但具有不同参数的函数。覆盖仅与派生类有关,其中父类定义了一个方法,而派生类希望覆盖该方法。

In PHP, you can only overload methods using the magic method __call.

在 PHP 中,您只能使用魔术方法重载方法__call

An example of overriding:

覆盖的一个例子:

<?php

class Foo {
   function myFoo() {
      return "Foo";
   }
}

class Bar extends Foo {
   function myFoo() {
      return "Bar";
   }
}

$foo = new Foo;
$bar = new Bar;
echo($foo->myFoo()); //"Foo"
echo($bar->myFoo()); //"Bar"
?>

回答by Andrew Moore

Function overloading occurs when you define the same function name twice (or more) using different set of parameters. For example:

当您使用不同的参数集定义相同的函数名称两次(或多次)时,就会发生函数重载。例如:

class Addition {
  function compute($first, $second) {
    return $first+$second;
  }

  function compute($first, $second, $third) {
    return $first+$second+$third;
  }
}

In the example above, the function computeis overloaded with two different parameter signatures. *This is not yet supported in PHP. An alternative is to use optional arguments:

在上面的例子中,函数compute被两个不同的参数签名重载。*PHP 尚不支持此功能。另一种方法是使用可选参数:

class Addition {
  function compute($first, $second, $third = 0) {
    return $first+$second+$third;
  }
}


Function overriding occurs when you extend a class and rewrite a function which existed in the parent class:

当您扩展类并重写父类中存在的函数时,会发生函数覆盖:

class Substraction extends Addition {
  function compute($first, $second, $third = 0) {
    return $first-$second-$third;
  }
}

For example, computeoverrides the behavior set forth in Addition.

例如,compute覆盖 中规定的行为Addition

回答by Christian

Strictly speaking, there's no difference, since you cannot do either :)

严格来说,没有区别,因为你不能做任何一个:)

Function overriding could have been done with a PHP extension like APD, but it's deprecated and afaik last version was unusable.

函数覆盖可以使用像 APD 这样的 PHP 扩展来完成,但它已被弃用,并且 afaik 上一个版本无法使用。

Function overloading in PHP cannot be done due to dynamic typing, ie, in PHP you don't "define" variables to be a particular type. Example:

由于动态类型,PHP 中的函数重载无法完成,即,在 PHP 中您没有将变量“定义”为特定类型。例子:

$a=1;
$a='1';
$a=true;
$a=doSomething();

Each variable is of a different type, yet you can know the type before execution (see the 4th one). As a comparison, other languages use:

每个变量都是不同的类型,但您可以在执行之前知道类型(参见第四个)。作为比较,其他语言使用:

int a=1;
String s="1";
bool a=true;
something a=doSomething();

In the last example, you must forcefully set the variable's type (as an example, I used data type "something").

在最后一个示例中,您必须强制设置变量的类型(例如,我使用了数据类型“something”)。



Another "issue" why function overloading is not possible in PHP: PHP has a function called func_get_args(), which returns an array of current arguments, now consider the following code:

另一个“问题”为什么在 PHP 中不能进行函数重载:PHP 有一个名为 func_get_args() 的函数,它返回一个当前参数数组,现在考虑以下代码:

function hello($a){
  print_r(func_get_args());
}

function hello($a,$a){
  print_r(func_get_args());
}

hello('a');
hello('a','b');

Considering both functions accept any amount of arguments, which one should the compiler choose?

考虑到这两个函数都接受任意数量的参数,编译器应该选择哪一个?



Finally, I'd like to point out why the above replies are partially wrong; functionoverloading/overriding is NOT equal to methodoverloading/overriding.

最后,我想指出为什么上述回复有部分错误; 函数重载/覆盖不等于方法重载/覆盖。

Where a method is like a function but specific to a class, in which case, PHP does allow overriding in classes, but again no overloading, due to language semantics.

方法就像一个函数但特定于一个类,在这种情况下,PHP 允许在类中覆盖,但由于语言语义,不允许重载。

To conclude, languages like Javascript allow overriding (but again, no overloading), however they may also show the difference between overriding a user function and a method:

总而言之,像 Javascript 这样的语言允许覆盖(但同样不允许重载),但是它们也可能显示覆盖用户函数和方法之间的区别:

/// Function Overriding ///

function a(){
   alert('a');
}
a=function(){
   alert('b');
}

a(); // shows popup with 'b'


/// Method Overriding ///

var a={
  "a":function(){
    alert('a');
  }
}
a.a=function(){
   alert('b');
}

a.a(); // shows popup with 'b'

回答by Christian

Overloading Example

重载示例

class overload {
    public $name;
    public function __construct($agr) {
        $this->name = $agr;
    }
    public function __call($methodname, $agrument) {
         if($methodname == 'sum2') {

          if(count($agrument) == 2) {
              $this->sum($agrument[0], $agrument[1]);
          }
          if(count($agrument) == 3) {

              echo $this->sum1($agrument[0], $agrument[1], $agrument[2]);
          }
        }
    }
    public function sum($a, $b) {
        return $a + $b;
    }
    public function sum1($a,$b,$c) {

        return $a + $b + $c;
    }
}
$object = new overload('Sum');
echo $object->sum2(1,2,3);

回答by sbrbot

Although overloading paradigm is not fully supported by PHP the same (or very similar) effect can be achieved with default parameter(s) (as somebody mentioned before).

尽管 PHP 不完全支持重载范式,但使用默认参数可以实现相同(或非常相似)的效果(正如之前有人提到的)。

If you define your function like this:

如果你这样定义你的函数:

function f($p=0)
{
  if($p)
  {
    //implement functionality #1 here
  }
  else
  {
    //implement functionality #2 here
  }
}

When you call this function like:

当你像这样调用这个函数时:

f();

you'll get one functionality (#1), but if you call it with parameter like:

您将获得一项功能(#1),但如果您使用以下参数调用它:

f(1);

you'll get another functionality (#2). That's the effect of overloading - different functionality depending on function's input parameter(s).

你会得到另一个功能(#2)。这就是重载的效果——不同的功能取决于函数的输入参数。

I know, somebody will ask now what functionality one will get if he/she calls this function as f(0).

我知道,现在有人会问,如果他/她将此函数称为 f(0),将会获得什么功能。

回答by Ram Iyer

I would like to point out over here that Overloading in PHP has a completely different meaning as compared to other programming languages. A lot of people have said that overloading isnt supported in PHP and by the conventional definition of overloading, yes that functionality isnt explicitly available.

我想在这里指出,与其他编程语言相比,PHP 中的重载具有完全不同的含义。很多人都说 PHP 不支持重载,并且按照重载的传统定义,是的,功能不是明确可用的。

However, the correct definition of overloading in PHP is completely different.

但是,PHP 中重载的正确定义是完全不同的。

In PHP overloading refers to dynamically creating properties and methods using magic methods like __set() and __get(). These overloading methods are invoked when interacting with methods or properties that are not accessible or not declared.

在 PHP 中,重载是指使用 __set() 和 __get() 等魔术方法动态创建属性和方法。这些重载方法在与不可访问或未声明的方法或属性交互时被调用。

Here is a link from the PHP manual : http://www.php.net/manual/en/language.oop5.overloading.php

这是 PHP 手册中的链接:http: //www.php.net/manual/en/language.oop5.overloading.php

回答by Mashuq Tanmoy

There are some differences between Function overloading & overriding though both contains the same function name.In overloading ,between the same name functions contain different type of argument or return type;Such as: "function add (int a,int b)" & "function add(float a,float b); Here the add() function is overloaded. In the case of overriding both the argument and function name are same.It generally found in inheritance or in traits.We have to follow some tactics to introduce, what function will execute now. So In overriding the programmer follows some tactics to execute the desired function where in the overloading the program can automatically identify the desired function...Thanks!

函数重载和覆盖虽然包含相同的函数名,但还是有一些区别的。 function add(float a,float b); 这里的add()函数是重载的,在覆盖的情况下,参数和函数名都一样,一般出现在继承或者traits中。我们要按照一些技巧来介绍, 现在将执行什么函数。所以在重写程序员遵循一些策略来执行所需的函数,在重载时程序可以自动识别所需的函数......谢谢!

回答by user3040433

Overloading:In Real world, overloading means assigning some extra stuff to someone. As as in real world Overloading in PHP means calling extra functions. In other way You can say it have slimier function with different parameter.In PHP you can use overloading with magic functions e.g. __get, __set, __call etc.

重载:在现实世界中,重载意味着将一些额外的东西分配给某人。就像在现实世界中一样在 PHP 中重载意味着调用额外的函数。换句话说,您可以说它具有带有不同参数的更纤细的函数。在 PHP 中,您可以使用魔术函数重载,例如 __get、__set、__call 等。

Example of Overloading:

重载示例:

class Shape {
   const Pi = 3.142 ;  // constant value
  function __call($functionname, $argument){
    if($functionname == 'area')
    switch(count($argument)){
        case 0 : return 0 ;
        case 1 : return self::Pi * $argument[0] ; // 3.14 * 5
        case 2 : return $argument[0] * $argument[1];  // 5 * 10
    }

  }

 }
 $circle = new Shape();`enter code here`
 echo "Area of circle:".$circle->area()."</br>"; // display the area of circle Output 0
 echo "Area of circle:".$circle->area(5)."</br>"; // display the area of circle
 $rect = new Shape();
 echo "Area of rectangle:".$rect->area(5,10); // display area of rectangle

Overriding :In object oriented programming overriding is to replace parent method in child class.In overriding you can re-declare parent class method in child class. So, basically the purpose of overriding is to change the behavior of your parent class method.

覆盖:在面向对象编程中,覆盖是替换子类中的父方法。覆盖可以在子类中重新声明父类方法。所以,基本上覆盖的目的是改变你的父类方法的行为。

Example of overriding :

覆盖示例:

class parent_class
{

  public function text()    //text() is a parent class method
  {
    echo "Hello!! everyone I am parent class text method"."</br>";
  }
  public function test()   
  {
    echo "Hello!! I am second method of parent class"."</br>";
  }

}

class child extends parent_class
{
  public function text()     // Text() parent class method which is override by child 
  class
  {
    echo "Hello!! Everyone i am child class";
  }

 }

 $obj= new parent_class();
 $obj->text();            // display the parent class method echo
 $obj= new parent_class();
 $obj->test();
 $obj= new child();
 $obj->text(); // display the child class method echo

回答by Shriyash Deshmukh

Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.

当两个或多个方法名称相同但单个类中的参数数量不同时,就会发生方法重载。PHP 不支持方法重载。方法覆盖是指两个不同类中具有相同方法名称和相同数量参数的两个方法,即父类和子类。

回答by PHP Ferrari

PHP 5.x.x does not support overloading this is why PHP is not fully OOP.

PHP 5.xx 不支持重载,这就是 PHP 不是完全 OOP 的原因。