Skip to content

Latest commit

 

History

History
168 lines (142 loc) · 3.33 KB

类的关系.md

File metadata and controls

168 lines (142 loc) · 3.33 KB

类间关系

依赖关系

1.依赖和关联很像,但是不属于关联,他和关联的区别在于类与类直接没有关系,只是存在调用,比如学生登陆需要记一次日志。

<?php
class Student{

  //第一种方式
  public function studentLoginLog(Log $log){
      $log->studentLogin();
  }

  //第二种方式
  public function studentLoginLog(){
      Log::write();
  }

  //第三种
  public function studentLoginLog(){
      $log = new Log();
      $log -> write();
  }
}

关联关系

1.关联关系是一种在类中调用其它类的关系。
2.关联包括三种(关联、聚合、合成)。
3.关联关系可以是单向关联也可以是双向关联。 4.一般用于两个类是平级有关联关系的类中。

比如学生和老师就属于一种双向关联关系,学生有老师,老师有学生,同时学生和老师都可以脱离彼此单独存在。

<?php
class Teacher{
  private $student = null;

  //第一种方式
  public function __construct(Student $student){
    $this->student = $student;
  }

  //第二种方式
  public function setStudent(Student $student){
    $this->student = $student;
  }

  //调用
  public function getMyStudents(){
    $this->student->getStudents();
  }
}
<?php
class Student{
  private $teacher = null;

  //第一种方式
  public function __construct(Teacher $teacher){
    $this->teacher = $teacher;
  }

  //第二种方式
  public function setTeacher(Teacher $teacher){
    $this->teacher = $teacher;
  }

  //调用
  public function getMyTeacher(){
    $this->teacher->getTeacher();
  }
}

聚合关系

1.聚合用来表示类的从属关系,比如学生和课本,学生拥有课本,但是课本又不只是学生有老师也有,所以课本可以脱离学生存在。

<?php
class Student{
  private $book = null;

  //第一种方式
  public function __construct(Book $book){
    $this->book = $book;
  }

  //第二种方式
  public function setBook(Book $book){
    $this->book = $book;
  }

  //调用
  public function getMyBook(){
    $this->teacher->getBook();
  }
}

组合关系

1.组合是一种强关联关系,一个类不能脱离另一个类,比如学生和成绩。

<?php
class Student{
  private $grades = null;

  //第一种方式
  public function __construct(){
    $this->grades =new Grades();
  }

  //第二种方式
  public function setBook(){
      $this->grades =new Grades();
  }

  //调用
  public function getMyBook(){
    $this->grades->getGrades();
    //或者
    (new Grades()) ->getGrades();
  }
}

泛化

泛化就是继承子类拥有父类的所有属性方法,同事也可以复写他们。

<?php
class User{

  public function __construct(){}

  public function getUserName(){
      reutrn 'userName';
  }
}

class Student{
  public function __construct(){}

  public function getUserName(){
    reutn 'studentName';
  }
}

实现

接口是用于定义行为规范,实现接口的类必须完成接口的所有方法。

<?php
interface class{
    public function onClass();
}

class Student implement class{
  public function onClass(){
    echo 'Student on class';
  }
}

class Teacher implement class{
  public function onClass(){
    echo 'Teacher on class';
  }
}

###强弱顺序 实现 = 泛化 > 组合 > 聚合 > 关联 > 依赖