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

后端 未结 2 1642
生来不讨喜
生来不讨喜 2021-02-15 00:34

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         


        
相关标签:
2条回答
  • 2021-02-15 01:14

    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)

    0 讨论(0)
  • 2021-02-15 01:22

    The example did not show a typical specialization pattern where b does not need to know implementation details of call() but can specify how test() is to be done. And it does return 1 unfortunately. However by declaring the function protected instead of private, it will work as expected.

    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();
    
    0 讨论(0)
提交回复
热议问题