zoukankan      html  css  js  c++  java
  • php学习十一:组合

    我们在类当中我往往会用到一些对象,此时的继承就无法满足我们的需求,这个时候我们需要用到组合。继承如果是is..a的关系,那么组合就是has...a的关系,直接在本类里面声明即可,不过声明的是一个对象

    代码:我定义一个Score类,作为Student类的一个组合类

    class Score
    {
        public $english;
        public $chinese;
        public $math;
        function __construct($english,$chinese,$math)
        {
            $this->chinese = $chinese;
            $this->english = $english;
            $this->math = $math;
        }
    }
    

      

    class Student
    {
        public $name;
        public $age;
        public $Score;
        function __construct($name,$age,Score $Score)
        {
            $this->name = $name;
            $this->age = $age;
            $this->Score = $Score;  //对象
        }
        function show(){
            echo "我叫{$this->name},今年{$this->age}岁了,
            数学:{$this->Score->math},英语:{$this->Score->english},
            语文:{$this->Score->chinese}。";
        }
    
    }
    

      

    在main主页面进行实例化

    include_once "Score.class.php";
    include_once "Student.class.php";
    $score = new Score(100,99,98);
    $student = new Student("房明",18,$score);
    $student->show();
    

      

  • 相关阅读:
    ubuntu18 任务栏调到底部
    十六, Oracle约束
    十五, 数据导出导入
    十四, 角色
    十三,权限
    十二, 系统默认参数
    十一,函数
    PL/SQL 九九乘法表
    十,事务和锁
    九, 表查询 三
  • 原文地址:https://www.cnblogs.com/mmykdbc/p/6647429.html
Copyright © 2011-2022 走看看