views:

364

answers:

1

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

+5  A: 

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)

Yacoby
Thanks for the demo,I understand what virtual means now.But can you also prove it with PHP?Because seems in PHP it's impossible to convert an object to the base class,in other words,there is no such concept as virtual in PHP?
There is no such concept as virtual in php. Or the other way round, every method is virtual since the actual implementation is looked up at runtime.
VolkerK
I think it's better to think there's no virtual concept in PHP,as it's impossible to do this in this language:`Foo* f = new Bar();`
But you have `instanceof` and the ability to overwrite methods.
VolkerK