PHP程序员小白到大牛集训(12期免息)

使用构造器和访问类接口获取私有和受保护的数据

原创2019-01-20 15:59:57128
摘要:<?php // 类成员的访问限制有分:// public 公共,外部可访问// private 私有,仅在本类中访问// protected 受保护,仅类内部和子类中使用class Stu{ public $name; private $age; protected $sex; public function __construct($name,$sex,$age)//构造器,初

<?php 

// 类成员的访问限制有分:

// public 公共,外部可访问

// private 私有,仅在本类中访问

// protected 受保护,仅类内部和子类中使用


class Stu

{

public $name;


private $age;


protected $sex;



public function __construct($name,$sex,$age)//构造器,初始化

{

$this-> name = $name;

$this-> age = $age;

$this-> sex = $sex;

}


public function get_age()//创建接口,访问受限的数据,为保障数据安全建议添加判断来返回

{

return $this->age;

}


public function get_sex()//创建接口,访问受限的数据,为保障数据安全建议添加判断来返回

{

return $this->sex;

}

}



$stu = new Stu('名称','女','18');


echo '学生姓名是:',$stu->name, '性别是:',$stu->get_sex,'年龄是:',$stu->get_age(),'<br>';


echo '<hr>';



?>


批改老师:韦小宝批改时间:2019-01-20 17:44:16
老师总结:写的很不错 权限在一个函数中是很重要的 这一点必须要弄明白

发布手记

热门词条