V
V
vrazbros2021-05-09 19:12:55
PHP
vrazbros, 2021-05-09 19:12:55

Why is the public method not inherited in this PHP code?

I understand OOP, I came across such a code, it seems simple, but I can’t understand

<?php
abstract class base {
    public function inherited() {
        $this->overridden();
    }
    private function overridden() {
        echo 'base';
    }
}

class child extends base {
    private function overridden() {
        echo 'child';
    }
}

$test = new child();
$test->inherited();
?>

Output will be "base".


I can't figure out why base outputs ? After all, the child class inherited the inherited public method, which means it had to call the private overridden method from the child class and display child

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2021-05-09
@vrazbros

Inherited does not mean "copied". It's just that when calling $test->inherited() in the child class, the function will not be found and there will be an attempt to call the function from the parent class base.
Well, the base class, as Lentyuy already wrote , does not see overriden() from child, since it is private.

L
Lazy @BojackHorseman PHP, 2021-05-09
Tag

inherited.
and not the method that you expect is called, because in the context of base nothing is known about child:: overridden (), because it is private. if you remove the base::overridden() declaration, there will be an error.

A
AlexSer, 2021-05-10
@AlexSer

You have it private, it can only be called within its class!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question