<?php
class Par {
private $data;
public function setParentData() {
$this->data = 'Parent';
}
public function showParentData() {
echo 'Par::data = ', $this->data, '<br>';
echo 'I know you have $', $this->money, '.<br>';
echo 'But I don\'t know your data.<br>';
}
}
class Me extends Par {
public $data;
public $money;
public function setData() {
$this->data = 'Me';
$this->money = 63;
}
public function showData() {
echo 'Me::data = ', $this->data, '<br>';
echo 'Me::money = ', $this->money, '<br>';
}
}
$me = new Me();
$me->setData();
$me->setParentData();
$me->showParentData();
$me->showData();
輸出:
Par::data = Parent
I know you have $63.
But I don't know your data.
Me::data = Me
Me::money = 63
所以,當父類的data變數為private時,父類不能訪問子類的同名變數data,子類也不能通過parent::$data訪問父類的data變數。