What's the equivalent of virtual functions of

2019-03-25 23:55发布

问题:

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()
 {
  echo 1;
 }
}

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

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

The output is 2

回答1:

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)



回答2:

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();


回答3:

use static keyword (php 5.4) not $this->meth() but static::meth()