Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP inhertience method referencing

Tags:

oop

php

<?php
class A {
    private function foo() {
        echo "baf!<br/>";
    }
    public function test() {
        $this->foo();

    }
}


class C extends A {
    private function foo() {
        echo "bar!<br/>";
    }

}

$c = new C();
$c->test();  //Prints baf!
?> 

How to make c->test() to print bar! ? I was expecting that foo() will be overridden in C and would print bar! can someone explain it to me?

like image 263
varuog Avatar asked Jul 10 '15 03:07

varuog


People also ask

Are PHP objects passed by reference?

In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value. It only contains an object identifier which allows using which the actual object is found.

How inheritance is implemented in PHP?

Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.

How do I reference a class in PHP?

You just can do so, as you have only instantiated once, you can refer to that instance with the $instance variable. Additionally you can "reference" that $instance as well in some other variable: $reference = $instance; You can now access the single instance of Class with the $instance and the $reference variable.

What are the __ construct () and __ destruct () methods in a PHP class?

Example# __construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion.


1 Answers

By making both methods protected you will achieve the desired result; the reason being that within A::test() it can only resolve $this->foo() to A::foo() because of the private visibility. See Visibility.

class A {
    protected function foo() {
        echo "baf!<br/>";
    }
    public function test() {
        $this->foo();

    }
}


class C extends A {
    protected function foo() {
        echo "bar!<br/>";
    }

}

$c = new C();
$c->test();  //Prints bar!
like image 119
Ja͢ck Avatar answered Oct 11 '22 10:10

Ja͢ck