A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

*类属性与类常量

* 1.类属性仅允许使用以下类型的数据进行初始化

* 标量和数组字面量:字符串,数值,常量,数组,原型文档(php5.3+)

* 2.不允许使用:变量,表达式,对象

* 3.类常量使用关键字const声明,不允许设置访问限制符,强制为public,不能更改

* 4.类常量是属性类的,不属性它的某个实例对象,必须使用类才可以访问

* 5.访问类常量要使用范围解析符::,双冒号

* 在类中使用关键字self表示当前类,在外部可直接使用类名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
define('SITE_NAME','PHP中文网');
class User1
{
    //声明属性
    private $siteName = SITE_NAME;
    private $name = '老顽童';
    private $email = 'lwt@php.cn';
    private $course = ['php','java','python'];
    const LECTURE = '朱老师';
    //构造方法
    public function __construct($name='',$email='', $siteName='',array $course=[])
    {
        //如果传参,则使用新值初始化属性,否则使用默认值
        $name ? ($this->name = $name) : $this->name;
        $email ? ($this->email = $email) : $this->email;
        $siteName ? ($this->siteName = $siteName) : $this->siteName;
        $course ? ($this->course = $course) : $this->course;
         
    }
     
    //查询器
    public function __get($name)
    {
        return $this->$name;
    }
     
    //设置器
    public function __set($name,$value)
    {
        return $this->$name = $value;
    }
     
    //在类中访问类常量,使用self来引用当前类名
    public function getConst()
    {
        //类内部也可以直接使用当前类名
//        return User1::LECTURE;
        //推荐使用self:当类名改变时,不必修改内部对它的引用
        return self::LECTURE;
    }
}


1 个回复

倒序浏览
奈斯,感谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马