PHP 学校,班级,学生类的三级关系

<?php
/**
 * Created by PhpStorm.
 * User: yangy
 * Date: 2017/5/11
 * Time: 8:05
 */
//学校类
class School{
    private $SchoolName;
    private $classes=array();
    public function __construct()
    {
        $this->classes=array();
    }
    public  function &__get($property_name)
    {
        //echo "在直接获取私有属性值的时候,自动调用了这个__get()方法\n";
        if(isset($this->$property_name))
        {
            return($this->$property_name);
        }
        else
        {
            return(NULL);
        }
    }
    //__set()方法用来设置私有属性
    public  function __set($property_name, $value)
    {
        //echo "在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值\n";
        $this->$property_name = $value;
    }
}
//班级类
class SchoolClass{
    private $students;
    private $className;
    public function __construct()
    {
        $this->students=array();
    }
    public  function &__get($property_name)
    {
        if(isset($this->$property_name))
        {
            return($this->$property_name);
        }
        else
        {
            return(NULL);
        }
    }
    public  function __set($property_name, $value)
    {
        $this->$property_name = $value;
    }

}
//学生类
class Student{
    private $name;
    private $age;
    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
    public  function &__get($property_name)
    {
        if(isset($this->$property_name))
        {
            return($this->$property_name);
        }
        else
        {
            return(NULL);
        }
    }
    public  function __set($property_name, $value)
    {
        $this->$property_name = $value;
    }
}
function main(){
    $school=new School();
    $school->schoolName="XXX大学\n";
    for ($i=0;$i<10;$i++){
        array_push($school->classes,new SchoolClass());
        $school->classes[$i]->className="班级".$i;
        for ($j=0;$j<30;$j++){
            array_push($school->classes[$i]->students,new Student("学生".$j,$j+10));
        }
    }
    echo $school->schoolName;
    for ($i=0;$i<10;$i++){
        echo $school->classes[$i]->className."\n";
        for ($j=0;$j<30;$j++){
            echo "          ".$school->classes[$i]->students[$j]->name."    年龄".$school->classes[$i]->students[$j]->age."\n";
        }
    }
    //第二种遍历方式
    echo $school->schoolName;
    foreach ($school->classes as $class){
        echo $class->className."\n";
        foreach ($class->students as $student){
            echo "          ".$student->name."    年龄".$student->age."\n";
        }
    }
}

main();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值