php 封装 继承 例子,类的继承和封装

实例

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();

运行实例 »

点击 "运行实例" 按钮查看在线实例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值