实例
class Students
{
//属性
//公共属性
public $name;
public $age;
//private 私有属性
//private $score;
//受保护的属性
protected $score;
//构造方法
public function __construct($name,$age,$score)
{
$this->name=$name;
$this->age=$age;
$this->score=$score;
$this->getInfo();
}
//方法
public function hobby($hobby)
{
return $hobby;
}
// 方法: 获取当前实例的属性,即学生的基本信息
public function getInfo()
{
$res='学生的基本信息:'.'
';
$res.='姓名:'.$this->name.'
';
$res.='年龄:'.$this->age.'
';
$res.='学习成绩: '.var_export($this->score,true).'
';
$res.='爱好:'.$this->hobby('读书');
echo $res;
}
// 为了方便外部访问, 通常会给私有属性创建一个获取器方法
public function getScore()
{
return var_export($this->score, true);
}
}
//类实例化
$student1=new Students('小明',10,['语文'=>80,'数学'=>70,'英语'=>60]);
//echo '
'.$student1->getScore();
echo '
';
//扩展类
class Students1 extends Students
{
public $role;
public function __construct($name, $age, $score,$role)
{
$this->role=$role;
parent::__construct($name, $age, $score);
}
public function getInfo()
{
$res='学生的基本信息:'.'
';
$res.='姓名:'.$this->name.'
';
$res.='年龄:'.$this->age.'
';
//访问私有属性 $this->getScore();
$res.='学习成绩: '.var_export($this->getScore(),true).'
';
$res.='爱好:'.$this->hobby('读书').'
';
$res.='角色:'.$this->role;
echo $res;
}
//重写getScore()
public function getScore()
{
if($this->role==='班长'){
return var_export($this->score, true);
}else{
return '一般人不可见';
}
}
}
//类实例化
$student2=new Students1('小红',9,['语文'=>90,'数学'=>80,'英语'=>100],'学生');
echo '
';
echo $student2->getScore();
echo '
';
$student2->role='班长';
echo $student2->getScore();
运行实例 »
点击 "运行实例" 按钮查看在线实例