Cris
Cris

Reputation: 4044

Shouldn't $this refer to the current object?

I'm learning the differences between self, static and this and ran across this example from php.net:

<?php
class A {
    private function foo() {
        echo "success!\n";
    }
    public function test() {
        $this->foo();
        static::foo();
    }
}

class B extends A {
   /* foo() will be copied to B, hence its scope will still be A and
    * the call be successful */
}

class C extends A {
    private function foo() {
        /* original method is replaced; the scope of the new one is C */
    }
}

$b = new B();
$b->test();
$c = new C();
$c->test();   //fails
?>

The result is

success!
success!
success!


Fatal error:  Call to private method C::foo() from context 'A' in /tmp/test.php on line 9

My question is this: when creating the new object C, shouldn't the call $this->foo(); call the newly replaced private function foo inside class C (and return an error since it's private)?

Upvotes: 1

Views: 111

Answers (1)

Theo
Theo

Reputation: 1633

You should use protected rather than public to get this behaviour.

This is covered in a lot of detail here: What is the difference between public, private, and protected?

A quick excerpt:

  • public scope to make that variable/function available from anywhere, other classes and instances of the object.
  • private scope when you want your variable/function to be visible in its own class only.
  • protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.

Upvotes: 1

Related Questions