3
class Bar{        
    public function test(){
        $this->testPublic();
        $this->testPrivate();
    }

    public function testPublic(){
        echo "Bar::testPublic\n";
    }

    private function testPrivate(){
        echo "Bar::testPrivate\n";
    }        
}

class Foo extends Bar{
    public function testPublic(){
        echo "Foo::testPublic\n";
    }
    private function testPrivate(){
        echo "Foo::testPrivate\n";
    }

}

$myFoo = new Foo();
$myFoo->test();
//Foo::testPublic
//Bar::testPrivate

I'm having a lot of trouble understanding this output. Would someone be able to give me a clear succinct explanation of what is going on? I'm learning OOP and wanted to know how to use extensions to override the parent class functions.

0

2 Answers 2

5

The test() method calls 2 methods:

  1. testPublic - it's a public one, so it was overriden in the Foo. So the Foo::testPublic is called
  2. testPrivate - it's a private one, so it's only visible for each class itself. For the caller method (it's Bar) - it's a Bar::testPrivate

So - if the method is public or protected - it can be overriden and called from the ancestor/child; if it's private - it cannot.

Sign up to request clarification or add additional context in comments.

Comments

0

The $this references the current object. So when you do the following.

$this->testPublic();

It will call testPublic() for the top most class that implements that function.

If you want to only call the parent class, then there is the parent keyword.

parent::testPublic();

That will call testPublic() on the class below the current object.

Becare full not to confuse the -> operator with the :: operator.

The :: operator references the class definition of an object, where as -> references the instance of an object.

 self::testPublic();
 $foo::testPublic();

That references a static function called testPublic(), and static methods are defined at the class level.

 $foo->testPublic();
 $this->testPublic();

That references a function as part of the instance of an object, and there is a vtable used to look up which object instance level should be called.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.