Blogger Information
Blog 48
fans 0
comment 0
visits 36360
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类常量,对象初始化,属性重载-208.09.03
雨天的博客
Original
527 people have browsed it

实例

<?php
/**
 * 类常量,对象初始化,属性重载
 * 1.类常量可以创建对象之间的数据共享
 * 2.对象那个初始化,用构造方法,对象在创建之前自动调用,来完成对象的初始化工作
 * 3.在类的外部访问不存在或无权访问的属性时,会自动调用这些方法
 * 属性重载涉及4个方法:__get() __set() __isset() __unset()
 */
//类声名
class Person{
    const SITE_NAME = 'PHP';//声名类常量
    private $name;
    private $sex;
    private $salary;
    //类初始化
    function __construct($name,$sex,$salary)
    {
        $this->name = $name;
        $this->sex = $sex;
        $this->salary = $salary;
    }
    //获取属性的重载
    public  function __get($name)
    {
        if($name == 'salary')
        {
            return false;
        }
        return $this->$name;
    }
    //更新属性重载
    public function __set($name, $value)
    {
        if($name == 'salary')
        {
            echo '不能重写';
        }
        return $this->$name = $value;
    }
    //属性检测重载
    public  function __isset($name)
    {
        if($name == 'sex')
        {
            return false;
        }
        return isset($this->$name);
    }
    //属性销毁
    public function __unset($name)
    {
        if($name == 'salary')
        {
            return false;
        }
        unset($this->$name);
    }
}
echo Person::SITE_NAME.'<br>';//访问类常量
//实例化类
$person = new Person('tom','男',6000);
var_dump($person);
echo '<hr>';
//获取属性
echo $person->name.'<br>';
echo $person->salary;
//更新属性
$person->salary=5000;
echo $person->salary,'<br>';
//检测属性
echo isset($person->sex)?'存在':'不存在<br>';
//销毁属性
unset($person->name);
echo $person->sex;

运行实例 »

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


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!