zoukankan      html  css  js  c++  java
  • 关于【类】的有关题

    一:类的定义

    1.求数据平均数的例子

    class Stat
    {
        public static function getAvg ($arryNum) //定义静态方法来求平均值
        {
            $totalNum = count($arryNum); //获得数字总数
            if ($totalNum == 0) { //如果数字个数为0则返回null
                return null;
            } else {
                $sum = 0; //用变量$sum保存所有数字的和
                for ($i = 0; $i < $totalNum; $i ++) { //通过循环计算所有数字的和
                    $sum += $arryNum[$i];
                }
                return $sum / $totalNum; //返回平均数
            }
        }
    }
    <?php 
    
       include 'Stat.php';  //包含数据统计类
        $arrayNum = explode(',', $_POST['nums']);   //将提交数字保存到数组中
        echo '该组数字的平均数为' . Stat::getAvg($arrayNum);   //调用统计类的静态方法getAvg()求平均数
    }
    ?>

    2.使用重载方法实现不同数据类型的运算

    *建立父类,并在该类中定义统计方法execstat()方法,这个方法只有计算两个数和的功能

    class StatParent //定义数据统计父类
    {
        public function execStat ($var0, $var1) //定义数据统计方法
        {
            return intval($var0 + $var1); //返回2个数的和
        }
    }

    定义stat类继承自statparent类,在该类中重写统计方法execstat(),根据传递的数值,实现值类型的求和和字符串的拼接

    <?php
    require 'StatParent.php';
    class Stat extends StatParent
    {
        public function execStat ($var0, $var1) //重写数据统计方法
        {
            return is_numeric($var0) && is_numeric($var1) ? intval($var0 + $var1) : $var0 . $var1; //如果为数字则计算数字的和,不是数字则连接2个参数
        }
    }

    *is_numeric()方法用于判断指定内容是不是数字类型或字符串类型

    <?php 
        require 'Stat.php';  //包含数值统计类
        $stat = new Stat();  //实例数值统计类
        echo '统计结果为:' . $stat->execStat($_POST['txt1'], $_POST['txt2']);  //输出统计结果
    }
    ?>

    3.使用$this关键字调用汽车类自身的方法

    <?php
    class Car //定义汽车类
    {
        private $colorFlag; //颜色标识
        private $typeFlag; //类型标识
        public function __construct ($colorFlag, $typeFlag) //构造方法
        {
            $this->colorFlag = $colorFlag; //颜色标识初始化
            $this->typeFlag = $typeFlag; //类型标识初始化
        }
        public function getColor () //定义获取颜色方法
        {
            switch ($this->colorFlag) { //使用switch语句根据不用颜色获得标识获得颜色
                case 0:
                    $color = '红色';
                    break;
                case 1:
                    $color = '白色';
                    break;
                case 2:
                    $color = '黑色';
                    break;
                default:
                    $color = '宝石蓝';
            }
            return $color;
        }
        public function getType () //定义获得汽车类型方法
        {
            switch ($this->typeFlag) { //根据类型标识获得汽车类型
                case 0:
                    $type = '奔驰';
                    break;
                case 1:
                    $type = '宝马';
                    break;
                case 2:
                    $type = '奥迪';
                    break;
                default:
                    $type = '捷达';
            }
            return $type;
        }
        public function getInfo () //获得汽车信息
        {
            return '我的汽车是' . $this->getColor() . $this->getType(); //调用类内方法返回汽车信息
        }
    }
    <?php 
        require 'Car.php';  //包含汽车类
        $colorFlag = $_POST['color'];   //获得表单提交的颜色标识
        $typFlag = $_POST['type'];       //获得表单提交的类别标识
        $car = new Car($colorFlag, $typFlag);  //对汽车类进行实现化
        echo $car->getInfo();   //打印汽车信息
    }
    ?>

    *在类体内部,使用$this关键字访问被private、protected、public所修饰的属性和方法

    4.使用self关键字调用学生类自身的静态方法

    <?php
    class Student
    {
        public static function study ()   //定义学习方法
        {
            return '学习';
        }
        public static function read ()    //定义读书方法
        {
            return '读书';
        }
        public function getAllMethod ()   //定义getAllMethod()来获得类中所有方法
        {
            return '学生可以' . self::study() . '、' . self::read();
        }
    }
     <?php
       $student = new Student();
       echo $student->getAllMethod(); 
       ?>

    5.汽车类中的刹车方法和颜色属性

    <?php 
    class Car
    {
        public $color;    //汽车颜色属性
        
        public function __construct($color){   //构造方法
            $this->color = $color;  //汽车颜色初始化
        }
        
        public function stop(){    //定义汽车刹车方法
            return "汽车执行了刹车方法";
        }
    }
    <?php
    $color = '红色';
    $car = new Car($color);
    echo '汽车的颜色为 - ' . $car->color.'<br/>';
    echo '行驶过程中 - ' . $car->stop();
    ?>

    6.学生类中使用构造方法为学生信息初始化

    *构造方法是类中的一个特殊函数,当创建一个类的实例时,将会自动调用类的构造方法

    构造方法没有返回值类型和返回值,这是因为构造方法是在创建对象时自动调用的,并不是一个独立的函数,因此没有返回值。

    构造方法的主要功能是实现对类的初始化工作

    建立一个二维数组,存数据

    <?php
    $students = array(
        0 => array('0312310', '小明', '16', '北京西城区') ,
        1 => array('0312311', '小张', '16', '北京宣武区') ,
        2 => array('0312312', '小赵', '17', '北京海淀区')
    ); 

    定义学生类

    <?php
    class Student
    {
        private $id; //学生ID
        private $name; //学生名称
        private $age; //学生年龄
        private $address; //学生住址
        public function __construct ($id, $name, $age, $address) //构造方法,对学生信息初始化
        {
            $this->id = $id;
            $this->name = $name;
            $this->age = $age;
            $this->address = $address;
        }
        public function getId () //获得学生ID
        {
            return $this->id;
        }
        public function getName () //获得学生名称
        {
            return $this->name;
        }
        public function getAge () //获得学生年龄
        {
            return $this->age;
        }
        public function getAddress () //获得学生住址
        {
            return $this->address;
        }
    }

    用for循环,遍历数据

    <?php 
    require 'arrayDb.php';
    require 'Student.php';
    $count = count($students);
    ?>    
    <table border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#009933">
      <tr>
        <td width="100" height="22" bgcolor="#009933"><font color="#FFFFFF">学号</font></td>
        <td width="100" bgcolor="#009933"><font color="#FFFFFF">姓名</font></td>
        <td width="100" bgcolor="#009933"><font color="#FFFFFF">年龄</font></td>
        <td width="200" bgcolor="#009933"><font color="#FFFFFF">住址</font></td>
      </tr>
    <?php 
    for ($i=0; $i<$count; $i++){
        $stu = $students[$i];
        $student = new Student($stu[0], $stu[1], $stu[2], $stu[3]); 
    ?>  
      <tr>
        <td height="22" bgcolor="#FFFFFF"><?= $student->getId()?></td>
        <td bgcolor="#FFFFFF"><?= $student->getName()?></td>
        <td bgcolor="#FFFFFF"><?= $student->getAge()?></td>
        <td bgcolor="#FFFFFF"><?= $student->getAddress()?></td>
      </tr>
    <?php 
    }
    ?>  
    </table>

    7.圆类中使用const关键字定义圆周率常量

    <?php
    class Circle
    {
        const PI = '3.14'; //定义圆周率为3.14,也可以使用pi()函数
        private $radius; //圆半径
        public function __construct ($radius)
        { //构造方法,实现对圆半径初始化
            $this->radius = $radius;
        }
        public function getArea ()
        { //获取圆面积
            return self::PI * pow($this->radius, 2);
        }
    }
    <?php 
    
        require_once 'Circle.php';
        $circle = new Circle(2);
        echo '该圆的面积为:'.$circle->getArea();
    
    ?>   

    *类常量属于类本身而且区分大小写,在类体内和静态方法一样,都使用self关键字加::对常量进行引用

    *pow()方法:pow(x,y),pow() 函数返回 x 的 y 次方。

    二:类的访问修饰符

    8.public修饰,成为公有方法和属性,公有方法可以被类实例的对象在类的内部和类的子类中调用

    <?php
    //定义汽车类Car
    class Car
    {
        public function run () //定义行驶方法
        {
            return '行驶';
        }
        public function getStatus () //定义返回汽车状态方法
        {
            return '汽车目前正在' . $this->run();
        }
    }
    //定义小汽车类SmallCar,并使其继承汽车类Car
    class SmallCar extends Car
    {
        public function smallCarRun () //定义小汽车行驶方法
        {
            return '小汽车' . $this->run();
        }
    }
    <?php 
    require 'Car.php';
    $car = new Car();
    echo '(1)通过汽车类对象调用汽车类的行驶方法的结果:<br/>';
    echo $car->run() . '<br/>';
    echo '(2)通过汽车类的getStatus()方法调用汽车行驶方法的结果:<br/>';
    echo $car->getStatus() . '<br/>';
    echo '(3)通过汽车类的子类调用汽车类的汽车行驶方法的结果:<br/>';
    $smallCar = new SmallCar();
    echo $smallCar->smallCarRun() . '<br/>';
    ?>

    9.使用private关键字定义汽车的颜色属性

    private修饰,成为私有方法和属性,私有方法可以在类体内被调用,但不可以被类实例的对象和类的子类所调用

    <?php
    class Car //定义汽车类Car
    {
        private $color; //汽车颜色
        public function __construct ($color) //构造方法对类中属性初始化
        {
            $this->color = $color; //汽车颜色初始化
        }
        public function getColor () //定义获得汽车颜色的方法
        {
            return $this->color; //返回汽车颜色
        }
    }
    <?php 
    require 'Car.php';  //包含汽车类
    $color = '红色';   //指定汽车颜色
    $car = new Car($color);   //对汽车类实例化
    //echo '通过类实例的对象调用类的私有属性的结果:<br/>';
    //echo @'汽车颜色是:'.$car->color.'<br/>' or die('不能通过类的对象调用类中的私有方法<br/>');
    echo '在类中的方法中调用类的私有属性的结果:<br/>';
    echo '汽车颜色是:'.$car->getColor().'<br/>';  //打印汽车颜色
    ?>

    10.使用protected关键字定义汽车的保修年限

    *protected修饰,成为保护成员和方法,保护成员可以在类体内以及类的子类中被调用,但不可以在类体外被调用

    <?php
    class Car //定义汽车类Car
    {
        protected $repairTime; //汽车保修时间属性
        public function __construct ($repairTime) //构造方法对汽车的保修时间进行初始化
        {
            $this->repairTime = $repairTime;
        }
        public function getRepairTime () //获得汽车保修时间的方法
        {
            return $this->repairTime;
        }
    }
    class SmallCar extends Car //定义汽车类的子类SmallCar
    {
        public function __construct ($repairTime)
        {
            parent::__construct($repairTime); //调用父类构造方法对保修时间属性进行初始化
        }
        public function getSmallCarRepairTime () //调用父类的保修时间属性
        {
            return $this->repairTime;
        }
    }
    <?php 
    require 'Car.php';  //包含汽车类
    $repairTime = 3;      //定义保修年限
    $car = new Car($repairTime);   //对汽车类实例化
    //echo '通过类实例的对象直接调用类中的保护成员的结果<br/>';
    //echo '汽车保修年限为:'.$car->repairTime.'年<br/>';
    echo '在类体内调用保护成员的结果<br/>';
    echo '汽车保修年限为:'.$car->getRepairTime().'年<br/>';
    echo '在类子类中调用保护成员的结果<br/>';
    $repairTime = 5;      //定义保修年限
    $smallCar = new SmallCar($repairTime);
    echo '小汽车保修年限为:'.$smallCar->getSmallCarRepairTime().'年<br/>';
    ?>

    三:.类的继承:通过类的继承可以扩展父类的功能

    11.苹果子类继承水果父类

    <?php
    class Fruit //定义水果类
    {
        private $color; //颜色属性
        private $shape; //形状属性
        public function __construct ($color, $shape) //构造方法对水果类初始化
        {
            $this->color = $color;
            $this->shape = $shape;
        }
        public function getColor () //获得水果颜色
        {
            return $this->color;
        }
        public function getShape () //获得水果形状
        {
            return $this->shape;
        }
    }
    class Apple extends Fruit //苹果类继承水果类
    {
        public function __construct ($color, $shape) //构造方法对类进行初始化
        {
            parent::__construct($color, $shape);
        }
    }
     <?php 
       require 'Fruit.php';
       $apple = new Apple($_POST['color'], $_POST['shape']);
       echo '  <font color="blue">我看见的苹果是:'.$apple->getColor().','.$apple->getShape().'的</font>';
       ?> 

    *final关键字:如果父类中使用final关键字修饰的方法,在子类中是不能被重写的。如果一个类使用final修饰,则该类不能被继承

    12.使用parent关键字调用父类的方法

    *使用parent关键字不仅可以调用父类的普通方法,而且可以通过调用父类的构造方法实现对父类的初始化。

    *parent关键字不仅可以调用父类的普通成员,而且可以加“::”调用父类的静态成员。

    <?php
    class Car //定义汽车类
    {
        public function run () //定义行驶方法
        {
            return '行驶';
        }
    }
    class SmallCar extends Car //定义小汽车类,使之继承自汽车类
    {
        public function smallCarRun () //定义小汽车行驶方法
        {
            return '小汽车可以' . parent::run();
        }
    }
    <?php
    require 'Car.php';  //包含汽车类
    $car = new Car();  //对汽车类进行实例化
    echo $car->run() . '<br/>'; //调用汽车类行驶方法
    $smallCar = new SmallCar();  //实例小汽车类
    echo $smallCar->smallCarRun();  //调用小汽车类的行驶方法
    ?>

    13.苹果子类中覆盖水果父类的方法

    <?php
    class Fruit //定义水果类
    {
        public function getColor () //获得水果颜色
        {
            return '不同的水果颜色不同,无法确定';
        }
    }
    class Apple extends Fruit //苹果类继承水果类
    {
        private $color; //定义苹果颜色属性
        public function __construct ($color) //构造方法对类进行初始化
        {
            $this->color = $color;
        }
        public function getColor () //获得水果颜色
        {
            return '苹果的颜色是' . $this->color;
        }
    }
     <?php 
    require 'Fruit.php';
    $fruit = new Fruit();
    echo $fruit->getColor().'<br/>';
    $apple = new Apple('红色');
    echo $apple->getColor();
       ?> 

    四:抽象类和接口

    *抽象类:不能被实例化,只能被其他类所继承。抽象类的定义是在class前面加abstract。

    *接口是为了实现一种特定功能而预留的类似类的一种类型,只允许定义常量和方法,并且这里的方法没有任何的功能实现。

    14.美食抽象类

    <?php
    abstract class Food //美食类
    {
        private $material; //烹制材料
        public function __construct ($material) //父类构造方法
        {
            $this->material = $material;
        }
        public function getMaterial () //获得美食材料方法
        {
            return $this->material;
        }
    }
    class Bread extends Food //面包类继承美食类
    {
        public function __construct ($material) //子类构造方法
        {
            parent::__construct($material);
        }
    }
     <?php 
    require 'Food.php';
    $material = '面粉';
    //$food = new Food($material);
    //echo $food->getMaterial().'<br/>';
    $bread = new Bread($material);
    echo '制作面包的材料是:'.$bread->getMaterial().'<br/>';
       ?> 

    15.学生类多重接口的实现

    *在php中接口使用关键字interface声明,并且在类内部不能有属性,只能有方法,并且不能在方法中定义任何功能代码,例如:

    定义接口:

    interface name
    {
    public function fun1();
    private function fun2();
    }

    接口定义完成后,可以在定义类时使用关键字implements实现一个或者多个接口,所实现的多个接口名称之间使用逗号分隔:

    class Myclass implements interface1,interface2,interface3
    {
    需要实现各个接口中所声明的方法
    }

    例子:

    <?php
    interface Property_Id                            //编号接口
    {
        public function setId ($id);                    //方法声明
        public function getId ();
    }
    interface Property_Name                        //名称接口
    {
        public function setName ($name);             //方法声明
        public function getName ();
    }
    class Student implements Property_Id, Property_Name        //定义学生类,使其同时实现Property_Id和Property_Name两个接口
    {
        private $id;                                       //编号属性
        private $name;                                    //名称属性
        public function setId ($id)                           //实现接口中的各个方法
        {
            $this->id = $id;
        }
        public function getId ()
        {
            return $this->id;
        }
        public function setName ($name)
        {
            $this->name = $name;
        }
        public function getName ()
        {
            return $this->name;
        }
    }
     <?php 
    
        require 'Student.php';  //包含学生类
        $student = new Student();    //对学生类进行实例化
        $student->setId($_POST['id']);  //设定学生ID
        $student->setName($_POST['name']);  //设定学生名称
        echo '<font color="green">当前学生的学号是:'.$student->getId().' 姓名是:'.$student->getName().'</font>';  //打印学生信息
    
        ?>

    *require和include的区别

    只要程序运行就会将require语句所包含的文件包含进来,而include语句则是在执行到该语句时包含指定文件。

    五:类的多态:通过多态可以为类提供功能上的多种实现,php中通过继承或者接口实现类的多态

    16.通过继承实现多态

    <?php
    abstract class Animal //定义动物类
    {
        public function walk () //定义动物类中的行走方法
        {
            return '动物能行走';
        }
    }
    class Penguin extends Animal //定义企鹅类,并使其继承自动物类
    {
        public function walk () //重写父类中的walk()方法
        {
            return '企鹅可以直立行走';
        }
    }
    class Insect extends Animal //定义昆虫类,并使其继承自动物类
    {
        public function walk () //重写父类中的walk()方法
        {
            return '昆虫可以爬行';
        }
    }
    <?php 
    require 'Animal.php';
    $penguin = new Penguin();
    echo $penguin->walk();
    echo '<br/>';
    $insect = new Insect();
    echo $insect->walk();
    ?>    

    *企鹅类和昆虫类虽然都重写了父类的walk()方法,但是打印出的结果却不一样

    17.通过接口实现多态

    <?php
    interface Animal //定义动物接口
    {
        public function walk (); //声明行走的方法
    }
    class Penguin implements Animal //定义企鹅类,并使其实现动物接口
    {
        public function walk () //重写父类中的walk()方法
        {
            return '企鹅可以直立行走';
        }
    }
    class Insect implements Animal //定义昆虫类,并使其实现动物接口
    {
        public function walk () //重写父类中的walk()方法
        {
            return '昆虫可以爬行';
        }
    }
    <?php 
    require 'Animal.php';
    $penguin = new Penguin();
    echo $penguin->walk();
    echo '<br/>';
    $insect = new Insect();
    echo $insect->walk();
    ?>   

    *抽象类和接口的区别:

    在定义上, 在抽象类中可以对方法所实现的功能进行具体定义,而在接口中只能对方法进行声明,不能具体实现方法的功能。

    在用法上,继承抽象类的子类可以重写父类的方法,或通过实例后的对象直接调用父类中的方法,而实现接口的类中,必须包含所实现接口的所有方法

    六:常用关键字

    18.使用final关键字防止类被继承

    <?php
    class Fruit               //定义水果类
    {
        private $color;         //定义颜色属性
        public function __construct ($color)       //通过构造方法对颜色属性进行初始化
        {
            $this->color = $color; 
        }
        public function getColor ()   //获得水果颜色的方法
        {
            return $this->color;
        }
    }
    final class Apple extends Fruit  //定义final型的苹果类,使之继承子水果累
    {
        private $shape;  //定义形状属性
        public function __construct ($color, $shape)  //构造函数
        {
            parent::__construct($color);  //调用父类构造方法
            $this->shape = $shape;  //对形状属性进行初始化
        }
        public function getShape ()  //获得苹果的形状方法
        {
            return $this->shape;
        }
    }
    /*
    class Test extends Apple {      //定义一个Test测试类,使之继承final形的Apple类
        
    }
    */
    <?php 
        require 'Fruit.php';
        $apple = new Apple($_POST['color'], $_POST['shape']);
        echo '<font color="red">苹果是'.$apple->getColor().$apple->getShape().'的</font>';
    
    ?>

    19.使用static关键字定义类的静态成员

    <?php
    class Math //定义数值计算类
    {
        public static function add ($num1, $num2) //相加的方法
        {
            return $num1 + $num2;
        }
        public static function sub ($num1, $num2) //相减的方法
        {
            return $num1 - $num2;
        }
        public static function multi ($num1, $num2) //相乘的方法
        {
            return $num1 * $num2;
        }
        public static function div ($num1, $num2) //相除的方法
        {
            try {
                if ($num2 == 0) { //如果除数为0,则抛出异常
                    throw new Exception('除数不能为0');
                } else {
                    return $num1 / $num2;
                }
            } catch (Exception $e) {
                return $e->getMessage(); //如果除数为0,则给出错误提示
            }
        }
    }
    <body>
    <br />
    <div
        style=" 200px; padding: 3px; color: blue; clear: both; background-color: #E9F9C4; border: 1px solid #648B05; text-align: left; line-height: 30px;">
    数值计算器:<br />
    <form name="form1" method="post" action="<?=$_SERVER['PHP_SELF']?>"><input
        type="text" name="num1" class="input" size="20" /><br />
    <select name="type">
        <option value="">运算类别</option>
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">*</option>
        <option value="/">/</option>
    </select><br />
    <input type="text" name="num2" class="input" size="20" /> <input
        type="submit" value="求值" /></form>
    <?php
    if (isset($_POST['num1']) && trim($_POST['num1']) != '') { //判断是否提交了表单
        require 'Math.php'; //包含Math.php文件
        $num1 = $_POST['num1'];  //获得提交的数字
        $num2 = $_POST['num2'];
        switch ($_POST['type']) { 
            case '+':   //进行加运算
                $result = Math::add($num1, $num2);
                break;
            case '-':  //进行减运算
                $result = Math::sub($num1, $num2);
                break;
            case '*': //进行乘运算
                $result = Math::multi($num1, $num2);
                break;
            case '/': //进行除运算
                $result = Math::div($num1, $num2);
                break;
        }
        echo '结果:' . $result;  //打印计算结果
    }
    ?>
        </div>
    </body>
    </html>

    20.使用clone关键字实现对象的克隆

    <?php
    class Sheep
    {
        private $color; //颜色属性
        public function setColor ($color) //设置颜色的方法
        {
            $this->color = $color;
        }
        public function getColor () //获得颜色的方法 
        {
            return '羊的颜色是' . $this->color;
        }
    }
    <?php
    require 'Sheep.php'; //包含Sheep.php文件
    $sheep = new Sheep();  //对Sheep类进行实例化
    /*
    $sheep->setColor('白色');   //设置羊的颜色
    echo $sheep->getColor();  //打印羊的颜色
    $sheep1 = $sheep;   //将$sheep对象赋值给新对象$sheep1
    echo '<br/>';
    $sheep1->setColor('灰色');//通过新对象$sheep1调用设置颜色的方法
    echo $sheep->getColor();  //打印羊的颜色
    */
    
    $sheep->setColor('白色');  //设置羊的颜色
    echo $sheep->getColor();   //打印羊的颜色
    $sheep1 = clone $sheep;  //克隆$sheep对象,产生一个新的$sheep1对象
    echo '<br/>';
    $sheep1->setColor('灰色');  //通过新克隆的$sheep1对象调用Sheep类中的setColor()方法
    echo $sheep->getColor(); //打印羊的颜色
    ?>

    21.使用instanceof关键字,检测当前对象是属于哪个类

    <?php
    class Apple //定义苹果类
    {
        public function getColor () //获得苹果颜色方法
        {
            return '红色';
        }
    }
    class Orange //定义桔子类
    {
        public function getColor () //获得桔子颜色方法
        {
            return '橙色';
        }
    }
    <?php
    require 'Fruit.php';  //包含水果类
    function getColor ($obj)   //定义根据对象类型获得相应水果颜色的方法
    {
        if ($obj instanceof Apple) {  //判断是否为苹果实例的对象
            $str = '苹果是:';
        } elseif ($obj instanceof Orange) {  //判断是否为桔子实例的对象
            $str = '桔子是:';
        }
        return $str . $obj->getColor();  //打印结果
    }
    $apple = new Apple();  //对苹果类进行实例化
    $orange = new Orange();  //对桔子类进行实例化
    echo getColor($apple) . '<br/>';   //打印苹果颜色
    echo getColor($orange);  //打印桔子颜色
    ?>

    *is_a()函数判断指定的对象是否属于某类或其子类的对象。

    七:魔术方法:

    22.使用__set()方法为类中未声明的属性赋值

    <?php
    class Book //定义图书类
    {
        private $name; //书名
        private $page; //页码
        private $writer; //作者
        private $price; //价格
        private $other; //其他信息
        public function setName ($name) //设置书名
        {
            $this->name = $name;
        }
        public function getName () //获得书名
        {
            return $this->name;
        }
        public function setPage ($page) //设置页码
        {
            $this->page = $page;
        }
        public function getPage () //获得页码
        {
            return $this->page;
        }
        public function setWriter ($writer) //设置作者
        {
            $this->writer = $writer;
        }
        public function getWriter () //获得作者
        {
            return $this->writer;
        }
        public function setPrice ($price) //设置价格
        {
            $this->price = $price;
        }
        public function getPrice () //获得价格
        {
            return $this->price;
        }
        public function __set ($name, $value)
        {
            $this->other = $value;
        }
        public function getOther ()
        {
            return $this->other;
        }
    }

    定义数据

    <?php 
    require 'Book.php';
    $arrayBook = array(                          //图书信息数组,用于模拟图书信息表
        array('name'=>'《PHP从基础到**》', 'page'=>'650', 'writer'=>'小张、小潘、小王','price'=>'58'),
        array('name'=>'《PHP函数**》', 'page'=>'800', 'writer'=>'小潘、小王','price'=>'80'),
        array('name'=>'《PHP范例**》', 'page'=>'700', 'writer'=>'小李、小懂','price'=>'85'),
        array('name'=>'《PHP实战**》', 'page'=>'750', 'writer'=>'小郭、小刘','price'=>'75')
    );

    打印结果

    <?php 
    require 'db.php';
    foreach ($arrayBook as $key => $aBook) {
        $book = new Book();
        $book->setName($aBook['name']);
        $book->setPage($aBook['page']);
        $book->setWriter($aBook['writer']);
        $book->setPrice($aBook['price']);
        $book->bz = '备注';
    ?>
    
    <div style="100%; <?php if($key < count($arrayBook)-1){?>border-bottom:1px solid #0463BD;<?php } ?> clear:both;">
        <div style="160px; height:22px; line-height:22px; text-align:left; float:left;">
         <?php echo $book->getName()?>
        </div>
        <div style="160px; height:22px; line-height:22px; border-left:1px solid #0463BD; float:left;">
        <?php echo $book->getPage()?>
        </div>
        <div style="160px; height:22px; line-height:22px; border-left:1px solid #0463BD; float:left;">
        <?php echo $book->getWriter()?>
        </div>
        <div style="160px; height:22px; line-height:22px; border-left:1px solid #0463BD; float:left;">
        <?php echo $book->getPrice()?>
        </div>
        <div  style="156px; height:22px; line-height:22px; border-left:1px solid #0463BD; float:left;">
        <?php echo $book->getOther()?>
        </div>
    </div>
    <?php }?>
    </div>

    23.使用__get()方法获取未定义属性的名称

    <?php
    class Apple
    {
        private $color; //颜色
        private $shape; //形状
        private $weight; //重量
        public function __construct ($color, $shape, $weight) //构造方法
        {
            $this->color = $color;
            $this->shape = $shape;
            $this->weight = $weight;
        }
        public function getProperty ()
        {
            return '这个苹果重' . $this->weight . ',是' . $this->color . ',' . $this->shape . '的!';
        }
        public function __get ($name)
        { //使用__get()方法弹出未定义属性的提示
            echo '<script>alert("在类中未定义属性' . $name . '!");</script>';
        }
    }
    <?php
    require 'Apple.php';
    $apple = new Apple('红色', '圆形', '0.4kg');
    echo $apple->getProperty();
    echo $apple->produceArea;
    ?>

    24.使用__call()方法打印类中未定义方法的信息

    <?php
    class Book //图书类
    {
        private $name; //书名
        private $price; //价格
        public function __construct ($name, $price) //构造方法
        {
            $this->name = $name;
            $this->price = $price;
        }
        public function __call ($name, $arguments) //__call()方法
        {
            echo $name . '方法未定义';
        }
        public function getProperty () //获得图书信息的方法
        {
            return $this->name . '的价格是' . $this->price . '元';
        }
    }
    <?php
    require 'Book.php';  //包含Book.php文件
    $bookName = '《PHP范例**》';   //书名
    $price = '85';  //价格
    $book = new Book($bookName, $price);  //对Book类进行实例化
    echo $book->getProperty() . '<br/>';  //打印图书属性
    $book->getInfo($bookName, $price);   //调用类中未定义的getInfo()方法
    ?>

    25.使用__tostring()方法将类的实例转换为字符串

    <?php
    class Circle //计算圆面积类
    {
        private $radius; //圆半径属性
        public function __construct ($radius) //构造方法
        {
            $this->radius = $radius;
        }
        public function __toString () //定义__toString()方法
        {
            return "圆的面积是:" . (string) number_format((pi() * pow($this->radius, 2)), 2);
        }
    }
    <?php
    require 'Circle.php';
    $radius = 2;
    echo '圆的半径是:'.$radius.'<br/>';
    echo new Circle($radius);
    ?>

    *number_format()函数对数字进行格式化输出

    26.使用__isset()方法提示未定义的属性信息

    <?php
    class Person
    {
        private $name;   // 名称
        private $age;  //年龄
        private $weight;  //体重
        public function setName ($name) //设置名称
        {
            $this->name = $name;
        }
        public function getName () //获得名称
        {
            return $this->name;
        }
        public function setAge ($age)//设置年龄
        {
            $this->age = $age;
        }
        public function getAge ()  //获得年龄
        {
            return $this->age;
        }
        public function setWeight ($weight)//设置体重
        {
            $this->weight = $weight;
        }
        public function getWeight ()  //获得体重
        {
            return $this->weight;
        }
        public function __isset ($name)  //定义__isset()方法
        {
            echo '在类中未定义属性' . $name;
        }
    }
    <?php 
    require 'Person.php';  //包含Person.php文件
    $person = new Person();  //实例Person类
    $person->setName('小明');   //设置名称
    $person->setAge('12'); //设置年龄
    $person->setWeight('45公斤'); //设置体重
    isset($person->sex);   //判断是否在类中定义了sex属性
    echo '<br/>';  //换行
    echo $person->getName().'的年龄是:'.$person->getAge().'岁,体重是:'.$person->getWeight() ;  //打印信息
    ?>

    27.使用__unset()方法提示未定义的属性信息

    <?php
    class Car
    {
        private $brand; //品牌
        private $color; //颜色
        public function __construct ($brand, $color) //构造方法
        {
            $this->brand = $brand;
            $this->color = $color;
        }
        public function __unset ($name) //定义__unset()方法
        {
            echo '在' . __CLASS__ . '类中未定义' . $name . '属性';
        }
    }
    <?php 
    require 'Car.php';  //包含Car.php文件
    $car = new Car('奥迪', '黑色'); //使用new关键字实例Car类
    unset($car->price);  //使用函数unset()释放Car类中未定义的属性price
    ?>

    *魔术常量:

    __CLASS__:返回当前类的名称

    __LINE__返回当前php脚本的当前行的行号

    __FILE__返回当前php脚本的完整路径和文件名

    __FUNCTION__返回当前函数的名称

    __METHOD__返回当前类中成员方法的名称

    28.使用__autoload__方法自动导入类文件

    类文件:

    <?php
    class Apple //苹果类
    {
        public function getColor () //获得苹果颜色方法
        {
            return '苹果是红色的';
        }
    }
    
    <?php
    class Orange //桔子类
    {
        public function getColor () //获得桔子颜色的方法
        {
            return '桔子是橙色的';
        }
    }

    导入代码

    <?php
    function __autoload ($className)
    {
        $file = dirname(__FILE__) . '/class/' . $className . '.php';
        if (! file_exists($file)) {
            return false;
        } else {
            require_once $file;
        }
    }
    <?php 
    require 'autoload.php';
    $apple = new Apple();
    $orange = new Orange();
    echo $apple->getColor() . '<br/>';
    echo $orange->getColor();
    ?>
  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    分布式架构在农业银行的应用实践与展望
  • 原文地址:https://www.cnblogs.com/xingyue1988/p/6441617.html
Copyright © 2011-2022 走看看