<?php
/**
* 类的继承extends
* 类成员的访问控制:public,private,protected的用法
*/
header('content-type:text/html;charset=utf-8');
//父类
class Animal
{
public $name;
private $age=100;//声明一个私有属性 结论对于私有属性,只能在类内部使用,外部要访问,可以创建一个公共方法来提供外部接口
protected $weight=200;//声明一个受保护的属性。只能在当前类和子类中访问,外部也不可访问
//构造方法
public function __construct($name='动物')
{
$this->name = $name;
}
public function eat($food='肉')
{
return $this->name.'爱吃'.$food.'<br>';
}
//创建一个外部接口来访问私有属性
public function getAge()
{
return $this->age;
}//创建一个外部接口来访问私有属性
public function getWeight()
{
return $this->Weight;
}
}
//子类
class Dog extends Animal
{
public $color;
public function __construct($name = '动物',$color='黑色')
{
parent::__construct($name);
$this->color = $color;
}
public function eat($food = '肉',$newfood='菜')
{
return $this->color.'的'.$this->name.parent::eat().'不爱吃'.$newfood;
}
//在子类创建一个父类受保护属性的接口
public function getWeight()
{
return $this->weight;
}//在子类创建一个父类私有属性的接口
public function getAge()
{
return $this->age;
}
}
echo (new Dog)->name;//当前值返回动物 来自父类的默认值动物
echo (new Dog('狗'))->eat('骨头');//返回狗爱吃骨头
echo (new Dog)->color;//返回黑色 当前子类的默认值是黑色
echo (new Dog('泰迪','白色'))->eat('火腿肠','shi');//返回白色泰迪爱吃火腿肠,不爱吃shi
echo (new Animal())->getAge();//返回错误 属性是私有的 外部无法访问 需要创建一个接口 在父类创建好外部的访问接口即可访问
echo (new Animal())->getweight();//返回错误 属性是受保护的 解决方法 需要创建一个接口 在父类创建好外部的访问接口即可访问
//子类创建受保护属性的接口得出返回值200
echo (new Animal())->getWeight();//返回200,证明受保护的值可以在子类中访问
echo (new Animal())->getWeight();//返回错误,证明私有属性只能在内部访问
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号