Blogger Information
Blog 40
fans 0
comment 0
visits 29309
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类的知识--2019-06-13
小人物的博客
Original
1322 people have browsed it

1. 编写一个类,例如学生类,商品类, 体会private, protected, public的作用

实例

<?php

class students
{
    public $name;
    public $class;
    private $teacher;
    protected $score;


    //构造方法
    public function __construct($name, $class, $teacher, $score)
    {
        $this->name = $name;
        $this->class = $class;
        $this->teacher =$teacher;
        $this->score = $score;
    }

    public function getScore()
    {  //非主管老师为朱老师的不能查看
        return $this->teacher === '朱老师' ? $this->score : '无权查看';
    }
    public function setScore($value)
    {
        return $this->teacher === '朱老师' ? $this->score= $value : '无权更新';
    }
}

$obj = new students ('张三','一年一班','朱老师','88');
echo $obj->name ,'<br>';
echo $obj->getScore(),'<br>';
echo $obj->setScore(90) ;
echo '<br>';

运行实例 »

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

2. 实例演示类的继承环境中, 对封装成员访问的权限控制技术,要求用到protected, extends, 以及获取器方法

实例

<?php

class students
{
    public $name;
    public $score;


    //构造方法
    public function __construct($name, $score)
    {
        $this->name = $name;
        $this->score = $score;
    }

    public function getScore()
    {
        return '姓名:' . $this->name . '成绩:' . $this->score . '<br>';
    }
}

class stu1 extends students
{
    public $class;
    public function  __construct($name,$score,$class)
    {
        parent::__construct($name,$score);
        $this->class = $class;
    }
}

$stu2 = new stu1 ('张三','88','一年一班');

echo $stu2->class . '的' .  $stu2->name . '成绩:' . $stu2->score;

运行实例 »

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


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post