Blogger Information
Blog 38
fans 0
comment 1
visits 30403
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
构造方法,魔术方法的基本应用
1
Original
1102 people have browsed it

实例

<?php
/**
 * 1.类声明应该独立创建一个文件
 * 2.类文件名称必须与类名一致
 */

class GirlFriends4
{
    /**
     * 类的构造方法和查询器
     */
    /***
     * private:访问控制符:仅允许在当前类中被访问,
     * 外部不能访问,除非通过外部的接口:接口器/查询器
     */
    private $name='';

    private $age=0;
//public $age = 27+10;表达式;public $age =$name;变量public $age = new $name;对象

    private $stature=[];

//声明一个构造方法:在实例化类的时候自动调用
//构造方法:对象的初始化,对象克隆,对象的序列化,对象的销毁
//对象的初始化
    public function __construct($name,$age,array $stature)
    {
        $this->name = $name;
        $this->age= $age;
        $this->stature = $stature;
    }

 //查询器:__get($name),能被系统自动调用
    //不需要用户去调用::当访问没有权限读取的属性的时候,会自动触发
    public function __get($name)
    {

        return $this->$name;
    }
    //设置器
    public function __set($name,$val)
    {
        if($name == 'age'){
            if(in_array($val,range(14,120))){
                $this->$name = $val;
            }
       }else{
            $this->$name = $val;
        }

    }
}

运行实例 »

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

测试脚本


实例

<meta charset="UTF-8">
<?php
require './class/GirlFriends4.php';

$girlfriends4 = new GirlFriends4('叶筱葵',27,[88,89,90]);

echo $girlfriends4->name;
echo '<br>';

$girlfriends4->age = 10;
echo $girlfriends4->age;

运行实例 »

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


Correction status:Uncorrected

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
Author's latest blog post
  • 1
    2018-03-16 00:39:40
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!