문제

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?

도움이 되었습니까?

해결책

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
    }

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top