9

abstract function xxx吗?

我刚刚做了一个测试,似乎表明私有方法也是虚拟的?

class a {
 private function test()
 {
  echo 1;
 }
}

class b extends a {
 private function test()
 {
  echo 2;
 }
 public function call()
 {
  $this->test();
 }
}

$instance = new b;
$instance->call();

输出是2

4

3 回答 3

18

在 PHP 中,所有非私有函数都是虚拟的,因此无需将它们显式声明为虚拟。

简单地声明一个成员函数abstract意味着基类不能提供实现,但所有派生类都应该提供。将方法定义为抽象方法与在 C++ 中执行以下操作相同

virtual void foo() = 0;

这仅仅意味着派生类必须实现foo();

编辑:关于编辑的问题

b::call()无法访问a::test()。因此,在调用私有函数时,只会调用调用它的类中的那个。

编辑:关于评论:

(来自维基百科)

在面向对象的编程中,虚函数或虚方法是一种函数或方法,其行为可以在继承类中被具有相同签名的函数覆盖。

由于明确说明您在 C++ 中支付的费用的想法,您必须将函数声明为虚拟函数以允许派生类覆盖函数。

class Foo{
public:
    void baz(){
        std::cout << "Foo";
    }
};
class Bar : public Foo{
public:
    void baz(){
        std::cout << "Bar";
    }
};

int main(){
    Foo* f = new Bar();
    f->baz(); //baz is not virtual in Foo, so the output is Foo
}

将 baz 更改为虚拟

class Foo{
public:
    virtual void baz(){
        std::cout << "Foo";
    }
};
//Same Bar declaration

int main(){
    Foo* f = new Bar();
    f->baz(); //baz is virtual in Foo, so the output is Bar as it will call the derived function
}

f请注意,如果上面示例中的变量是类型的Bar*,或者Bar它是否Foo::baz()是虚拟的,因为预期的类型是已知的(程序员明确提供了它)

于 2010-03-21T16:06:51.010 回答
4

该示例没有显示典型的专业化模式,其中 b 不需要知道实现细节call()但可以指定如何test()完成。1不幸的是,它确实返回了。但是,通过将函数声明为受保护而不是私有,它将按预期工作。

class a {
    protected function test()
    {
        echo 1;
    }
    public function call() {
        $this->test();
    }
}

class b extends a {
    protected function test()
    {
      echo 2;
    }
}

$instance = new b();
$instance->call();
于 2012-11-28T17:59:18.000 回答
2

使用静态关键字(php 5.4)不是 $this->meth() 而是 static::meth()

于 2013-03-10T20:52:16.133 回答