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
.
private usually means that it can be accessed ONLY from within the class. I think this is expected behaviour.
From the PHP-Docs:
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.
That is exactly the difference between private and protected. Only I can see private variables but my family can see protected.