PHP中的函数重载和重写是什么?

发布于 2024-09-05 02:30:53 字数 51 浏览 3 评论 0原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

夏九 2024-09-12 02:30:53

重载是定义具有相似签名但具有不同参数的函数。 重写仅与派生类相关,其中父类已经定义了方法并且派生类希望重写该方法。

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

覆盖的示例:

<?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"
?>

Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method.

In PHP, you can only overload methods using the magic method __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"
?>
夏末染殇 2024-09-12 02:30:53

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

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

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

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

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

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

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

例如,compute 覆盖 Addition 中规定的行为代码>.

Function overloading is not supported by PHP. It 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 compute is overloaded with two different parameter signatures. *This is not yet supported in PHP. An alternative is to use optional arguments:

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, compute overrides the behavior set forth in Addition.

伴我心暖 2024-09-12 02:30:53

严格来说,没有什么区别,因为你不能这样做:)

函数重写可以使用像 APD 这样的 PHP 扩展来完成,但它已被弃用,并且据我所知,最后一个版本无法使用。

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

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

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

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

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


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

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


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

如果方法类似于函数但特定于类,在这种情况下,PHP 确实允许在类中重写,但由于语言语义,同样不允许重载。

总而言之,像 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'

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.

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:

$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").


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:

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;
function overloading/overriding is NOT equal to method overloading/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.

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:

/// 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'
再见回来 2024-09-12 02:30:53

重载示例

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

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);
停滞 2024-09-12 02:30:53

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

如果您这样定义函数:

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

当您像这样调用此函数时:

f();

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

f(1);

您将获得另一种功能 (#2)。这就是重载的效果 - 不同的功能取决于函数的输入参数。

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

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).

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:

f(1);

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

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

烟织青萝梦 2024-09-12 02:30:53

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

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.

冷心人i 2024-09-12 02:30:53

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

然而,PHP 中重载的正确定义却完全不同。

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

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

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.

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

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.

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

や莫失莫忘 2024-09-12 02:30:53

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

重载示例:

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

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

覆盖示例:

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

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.

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
煞人兵器 2024-09-12 02:30:53

函数重载和函数重载之间存在一些差异。尽管两者包含相同的函数名,但重写。在重载中,同名函数之间包含不同类型的参数或返回类型;例如:
“函数add(int a,int b)”& “函数add(浮点a,浮点b);
这里 add() 函数被重载。
在重写的情况下,参数和函数名都相同。它通常出现在继承或特征中。我们必须遵循一些策略来引入,现在将执行什么函数。
因此,在重写中,程序员遵循一些策略来执行所需的函数,其中在重载中,程序可以自动识别所需的函数......谢谢!

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!

沫雨熙 2024-09-12 02:30:53

重载:使用一组不同的参数多次声明一个函数,如下所示:

<?php

function foo($a) {
    return $a;
}

function foo($a, $b) {
    return $a + $b;
}

echo foo(5); // Prints "5"
echo foo(5, 2); // Prints "7"
?>

重写:通过重新声明来用新方法替换父类的方法,如下所示:

<?php

class foo {
    function new($args) {
        // Do something.
    }
}

class bar extends foo {
    function new($args) {
        // Do something different.
    }
}

?>

Overloading: Declaring a function multiple times with a different set of parameters like this:

<?php

function foo($a) {
    return $a;
}

function foo($a, $b) {
    return $a + $b;
}

echo foo(5); // Prints "5"
echo foo(5, 2); // Prints "7"
?>

Overriding: Replacing the parent class's method(s) with a new method by redeclaring it like this:

<?php

class foo {
    function new($args) {
        // Do something.
    }
}

class bar extends foo {
    function new($args) {
        // Do something different.
    }
}

?>
放手` 2024-09-12 02:30:53

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文