foo
isn't copied to B per se (it is inherited but invisible; see Gordon's comment below). B inherits A->foo
, which calls A->test
. To demonstrate, look at what happens when you echo __CLASS__
from within test
and foo
(and remove the static::foo()
call, which is causing the error):
class A {
private function foo() {
echo __CLASS__."->foo\n";
echo "success!\n";
}
public function test() {
echo __CLASS__."->test\n";
$this->foo();
}
}
Output:
A->test
A->foo
success!
A->test
A->foo
success!
This is one of the fundamentals of inheritance as it relates to information hiding/encapsulation. This allows you to do things like this:
class ListOfThings {
// internal structure (top secret!)
private $_list = array();
// add item to list
public function add($item) {
$this->_list[] = $item;
}
// return number of items in list
public function count() {
return count($this->_list);
}
}
class ListOfStates extends ListOfThings {
// do we have all 50 states?
public function allStatesListed() {
return $this->count() === 50;
}
// try to access internal structure of ListOfThings
public function accessInternalStructure() {
sort($this->_list);
}
}
$states = new ListOfStates;
$states->add('ME');
$states->add('NH');
$states->add('VT');
$states->add('RI');
$states->add('CT');
var_dump($states->count());
var_dump($states->allStatesListed());
$states->accessInternalStructure();
Output:
int(5)
bool(false)
Warning: sort() expects parameter 1 to be array, null given...
As you can see, ListOfStates
is able to use all the public functionality of ListOfThings
, even though those functions all depend on the private variable $_list
. That said, ListOfStates
cannot directly manipulate $_list
; it can only act on $_list
indirectly through the public functions defined in ListOfThings
.
Check out the Visibility page in the PHP documentation for more details on such things.