What's the equivalent of virtual functions of c++ in PHP?

后端 未结 3 1748
夕颜
夕颜 2021-02-15 00:59

Is it abstract function xxx?

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

class a {
 private function test         


        
3条回答
  •  北海茫月
    2021-02-15 01:25

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

    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;
    

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

    EDIT: Regarding edited question

    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: Regarding the comment:

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

    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
    }
    

    Change baz to be virtual

    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
    }
    

    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)

提交回复
热议问题