Question

While coding and using late static binding in PHP I found some strange behaviour. A child object created with static() in its parent class can access the private methods of its parent.

Here's an example:

class Attachment
{
  public static function createFromFile($file)
  {
    $attachment = new static();
    echo get_class($attachment) . PHP_EOL;
    $attachment->loadFromFile($file);
  }

  private function loadFromFile($file)
  {
    echo 'attachment';
  }
}

class PictureAttachment extends Attachment
{
  //...
}

PictureAttachment::createFromFile('example.txt');

Output:

PictureAttachment
attachment

Is this a correct behaviour?

Was it helpful?

Solution

Yes, this is correct. The class that is calling the private method is the same that is declaring it. It doesn't matter that it may or may not instantiate a child class. You just can't have any code in the child class calling the private method of the parent.

In other words:

class Foo {

    protected function bar() {
        $this->baz();
    }

    private function baz() { }

}

class Bar extends Foo {

    protected function bar() {
        parent::bar();   // <-- works
        parent::baz();   // <-- doesn't work
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top