Base class not permitted to access private member?

2019-08-03 22:02发布

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

3条回答
2楼-- · 2019-08-03 22:13

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-08-03 22:18

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.

查看更多
够拽才男人
4楼-- · 2019-08-03 22:23

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

查看更多
登录 后发表回答