Blogger Information
Blog 33
fans 3
comment 1
visits 23260
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类的构造方法、查询器、设置器的使用(5月2日课程)2018/05/14
箭里飘香
Original
773 people have browsed it

本实例演示了类的创建并通过完成构造方法对类成员的访问以及通过魔术方法__get()/__set()完成对类的查询及设置

类文件:

实例

<?php

/**
 *
 */

class GirlFriend1
{
    //类成员:属性、方法

    //类属性:初始化必须使用标量的字面量、数组
    private $name = '';
    private $age = 0;
    private $stature = [];

    //声明构造方法:实例化是自动调用
    //功能:对象初始化
    public function __construct($name, $age,array $stature)
    {
        $this->name = $name;
        $this->age = $age;
        $this->stature = $stature;
    }

    public function getName()
    {
        return $this->name;
    }
    public function getAge()
    {
        return $this->age;
    }
    public function getStature()
    {
        return print_r($this->stature,true);
    }
    //获取器
    public function __get($name)
    {
        return $this->$name;
    }
    //设置器
    public function __set($name,$value)
    {

        $this->$name = $value;
    }

}

运行实例 »

点击 "运行实例" 按钮查看在线实例

演示文件:

实例

<?php
/**
 *
 */
require './class/Girfriend1.php';

$girlfriend1 = new GirlFriend1('吴婷',22,[60,50,50]);
echo "构造方法访问结果:<br>";
echo $girlfriend1->getName();
echo "<br>";
echo $girlfriend1->getAge();
echo "<br>";
echo $girlfriend1->getStature();
echo "<hr>";
echo "魔术方法访问结果:<br>";
echo $girlfriend1->name;
echo "<br>";
echo $girlfriend1->age;
echo "<br>";
print_r($girlfriend1->stature);
echo "<hr>";
echo "使用魔术方法设置age=35";
echo "<br>";
$girlfriend1->age = 35;

echo $girlfriend1->age;

运行实例 »

点击 "运行实例" 按钮查看在线实例

实例

<?php
/**
 *
 */
require './class/Girfriend1.php';

$girlfriend1 = new GirlFriend1('吴婷',22,[60,50,50]);
echo "构造方法访问结果:<br>";
echo $girlfriend1->getName();
echo "<br>";
echo $girlfriend1->getAge();
echo "<br>";
echo $girlfriend1->getStature();
echo "<hr>";
echo "魔术方法访问结果:<br>";
echo $girlfriend1->name;
echo "<br>";
echo $girlfriend1->age;
echo "<br>";
print_r($girlfriend1->stature);
echo "<hr>";
echo "使用魔术方法设置age=35";
echo "<br>";
$girlfriend1->age = 35;

echo $girlfriend1->age;

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
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