Base class not permitted to access private member?

2019-08-03 22:12发布

问题:

I could have sworn that in standard OOP, you can access the private members of the concrete class from a method in the base class. Does PHP just implement this differently, or am I doing something wrong, or was my understanding entirely wrong?

<?php

class Base {
  public function __toString() {
    return $this->name;
  }
}

class Concrete extends Base {
  private $name;

  public function __construct($name) {
    $this->name = $name;
  }
}

$o = new Concrete('foobar');
echo $o;

The above code fragment throws Fatal error: Cannot access private property Concrete::$name on line 5. It works if I change the access level of $name to protected.

Demo

回答1:

private usually means that it can be accessed ONLY from within the class. I think this is expected behaviour.

From the PHP-Docs:

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.



回答2:

Exactly, private is totally private (my daily diary) even family members cant access. Protected is just protected (my car) from rest of the world but family can access.



回答3:

That is exactly the difference between private and protected. Only I can see private variables but my family can see protected.