PHP中c ++的虚函数等效于什么? [英] What's the equivalent of virtual functions of c++ in PHP?

查看:142
本文介绍了PHP中c ++的虚函数等效于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象函数xxx 吗?

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

I just made a test which seems to indicate a private method to be virtual too?

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

推荐答案

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

In PHP all none private functions are virtual so there is no need to explicitly declare them as virtual.

将成员函数声明为抽象只是意味着基类无法提供实现,而所有派生类都应提供。将方法定义为抽象与在C ++中执行以下操作相同

Declaring a member function as abstract simply means that the base class cannot provide an implementation but all deriving classes should. Defining the method as abstract is the same as doing the following in C++

virtual void foo() = 0;

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

Which simply means that deriving classes must implement foo();

编辑:关于已编辑的问题

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

b::call() cannot access a::test(). For this reason when calling private functions only the one in the class where it was called from will be called.

EDIT
关于评论:

EDIT: Regarding the comment:

(来自Wikipieda)

(From Wikipieda)


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

In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature.

由于要在C ++中明确说明要支付的费用,因此必须将函数声明为虚拟的,以允许派生类重写函数。

Due to the idea of explicitly stating what you pay for in C++, you have to declare functions as being virtual to allow derived classes to override a function.

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()是否是虚拟的都没有关系,因为预期的类型是已知的(程序员明确提供了

Note, if the variable f in the above sample was of type Bar* or Bar it wouldn't matter if Foo::baz() was virtual or not as the intended type is known (The programmer explicitly supplied it)

这篇关于PHP中c ++的虚函数等效于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆