在PHP中实现方法重写


Achieve Method Overriding in PHP

我已经在OOPS中实现了方法重写,但我不确定如何在PHP中实现方法重写。当你创建一个同名的函数时,它会在函数的重新声明方面给你一个错误。

PHP中的方法重写实际上非常简单。您只需指定基类,然后在派生类中创建一个具有相同名称的方法(函数)。

class BaseClass {
  public function first_method() {
    echo("Hello! I am the base!'n");
  }
  public function do_something() {
    echo("Hi, there! I am the base!'n");
  }
}
class AnotherClass extends BaseClass {
  public function do_something() {
    echo("Hi, there! I am a derivative!'n");
  }
}
$base_class = new BaseClass();
$another_class = new AnotherClass();
$base_class->do_something();
$another_class->do_something();
$another_class->first_method();

编辑以涵盖方法过载的可能问题:-)

如果您想询问方法重载的问题,那么您应该知道这在PHP中是不可能的。还有另一个功能最终会给你同样的结果:默认参数。以下是一个既适用于方法又适用于函数的潜在用例:

function first_function($a, $b=NULL) {
  echo($a);
  if($b!==NULL) {
    echo($b);
  }
}

这基本上与具有两个名为first_function的函数(例如,在C++中)相同,其中每个函数都有不同数量的参数,如下所示:

void first_function(int a) {
  cout << a << endl;
}
void first_function(int a, int b) {
  cout << a << endl;
  cout << b << endl;
}

避免传统方法重载更有意义,因为PHP是一种松散类型的语言。以两个参数数量相同的函数结尾会导致死胡同,因为PHP解释器无法确定您要调用这两个函数中的哪一个,因为PHP中没有类型敏感度。