Blogger Information
Blog 9
fans 1
comment 0
visits 7740
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
面向对象初体验 -- 2018年5月2日作业
hongda的博客
Original
779 people have browsed it

今天学习了面向对象编程,我先创造一个为person的类:

<?php

class person
{
    public $name = '';
    public $gender = '';
    private $age = 0 ;
    private $height = 0;
    private $weight = 0;


    public function __construct($name, $gender, $age, $height, $weight)
    {
        $this->name = $name;
        $this->gender = $gender;
        $this->age = $age;
        $this->height = $height;
        $this->weight = $weight;
    }

    public function __get($name)
    {
        // TODO: Implement __get() method.
        return $this->$name;
    }

    public function __set($name, $value)
{
    // TODO: Implement __set() method.
    if ($name == 'age'){
        if (in_array($value,range(14,120))){
            $this->$name = $value;
        }
    } elseif ($name == 'height'){
        if (in_array($value,range(50,300))){
            $this->$name = $value;
        }
    }else {
        $this->$name = $value;
    }
}
}

这个类里面含有构造方法,查询器和设置器

然后我们用下面的PHP 代码来调用这个类:

<?php

require './class/person.php';

$hongda = new person('hongda','male',25,178,70);

echo "Hello, your name is ".$hongda->name." .<br>";
echo "Your gender is ".$hongda->gender." .<br>";
echo "Your age is ".$hongda->age.' years old.<br>';
echo "Your height is ".$hongda->height.'cm.<br>';
echo "Your weight is ".$hongda->weight.'kg.<br>';

echo '<hr>';
$hongda->age = 18;

echo "Your age is ".$hongda->age.' years old.<br>';

$hongda->height = 180;
echo "Your height is ".$hongda->height.'cm.<br>';

结果如下:

001.png

以上, 我先实例化了类,然后用查询器得到了对象的每个属性的value,然后用设置器改变了对象的一些属性的值。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post