美文网首页
PHP面向对象综合练习

PHP面向对象综合练习

作者: kangyiii | 来源:发表于2017-03-08 16:06 被阅读0次

    定义一个"学生类"。并由此类实例化两个"学生对象"。该类包括姓名、性别、年龄等基本信息,并至少包括一个静态属性(表示学生总数)和一个自定义常量,以及包括构造方法和析构方法。该对象还可以调用一个方法来进行"自我介绍"(显示其中的所有属性和常量)。构造方法可以自动初始化一个学生的基本信息,并显示"xx加入公司,当前有xx个员工"

    <?php 
            class Teacher{
                public $name;
                public $workYear = 0;
                public $major = "PHP";
                function introMe(){
                    echo "我叫$this->name,我工作{$this->workYear}年,专业是$this->major";
                }
            }
            $t1 = new Teacher();
            $t1 -> name = "大牛";
            $t1 -> workYear = 12;
            $t1 -> introMe();
    
            class Student{
                public $name = "学生";
                public $gender = null;
                public $age = 18;
                static $sum = 0;
                const PI = 3.14;
                function __construct($name,$gender,$age){
                    $this->name = $name;
                    $this->gender = $gender;
                    $this->age = $age;
                    self::$sum++;
                    echo "<br/>{$name}加入易之盛,当前有".self::$sum."人";
                }
    
                function __destruct(){
                    echo $this->name."<br/>被销毁<br/>";
                } 
                function introMe(){
                    echo "<br/>我叫$this->name,我今年{$this->age}岁";
                    if($this->gender == true){
                        echo "男生";
                    }else if($this->gender == false){
                        echo "女生";
                    }else{
    
                    }
                }
            }
            $s1 = new Student("大牛",true,22);
            $s1->introMe();
            $s2 = new Student("中牛",true,24);
            $s2->introMe();
            $s3 = new Student("小牛",true,27);
            $s3->introMe();
        ?>
    

    打印结果:
    大牛加入易之盛,当前有1人
    我叫大牛,我今年22岁男生
    中牛加入易之盛,当前有2人
    我叫中牛,我今年24岁男生
    小牛加入易之盛,当前有3人
    我叫小牛,我今年27岁男生
    小牛被销毁
    中牛被销毁
    大牛被销毁

    相关文章

      网友评论

          本文标题:PHP面向对象综合练习

          本文链接:https://www.haomeiwen.com/subject/ynybgttx.html