请仔细看这句话 如果父类有私有的属性。那么父类的方法只为父类的私有属性服务。
下面通过一系列列子来加深理解.
这个例子看起来很奇怪,在子类中重新定义了一个属性$sal,系统却返回了父类的属性。
复制代码 代码如下:
class employee{
private $sal=3000;
//protected $sal=3000;
public function getSal(){
return $this->sal;
}
}
class Manager extends employee {
protected $sal=5000;
public function getParentSal(){
//这里返回的是父类的private属性.
return parent::getSal();
}
}
$manager = new Manager();
echo "PHP ".phpversion()."
";
echo $manager->getSal();
echo "
";
echo "parent's \$sal ".$manager->getParentSal();
?>
复制代码 代码如下:
PHP 5.3.8
3000
parent's $sal 3000
复制代码 代码如下:
class employee{
//private $sal=3000;
protected $sal=3000;
public function getSal(){
return $this->sal;
}
}
class Manager extends employee {
protected $sal=5000;
public function getParentSal(){
//这里返回的是父类的private属性.
return parent::getSal();
}
}
$manager = new Manager();
echo "PHP ".phpversion()."
";
echo $manager->getSal();
echo "
";
echo "parent's \$sal ".$manager->getParentSal();
?>
复制代码 代码如下:
PHP 5.3.8
5000
parent's $sal 5000
复制代码 代码如下:
class employee{
private $sal=3000;
public function getSal(){
return $this->sal;
}
}
class Manager extends employee {
private $sal=5000;
//重写过的方法
public function getSal(){
return $this->sal;
}
public function getParentSal(){
//这里返回的是父类的private属性.
return parent::getSal();
}
}
$manager = new Manager();
echo "PHP ".phpversion()."
";
echo $manager->getSal();
echo "
";
echo "parent's \$sal ".$manager->getParentSal();
?>
复制代码 代码如下:
PHP 5.3.8
5000
parent's $sal 3000
复制代码 代码如下:
class employee{
private $sal=3000;
public function getSal(){
return $this->sal;
}
}
class Manager extends employee {
protected $sal=5000;
public function getParentSal(){
return $this->sal;
}
}
$manager = new Manager();
echo "PHP ".phpversion()."
";
echo $manager->getSal();
?>
复制代码 代码如下:
PHP 5.3.8
3000
复制代码 代码如下:
class employee{
protected $sal=3000;
public function getSal(){
return $this->sal;
}
}
class Manager extends employee {
protected $sal=5000;
public function getParentSal(){
return $this->sal;
}
}
$manager = new Manager();
echo "PHP ".phpversion()."
";
echo $manager->getSal();
?>
复制代码 代码如下:
PHP 5.3.8
5000