類常量是PHP面向對象程序設計中非常重要的一個概念,牢固掌握類常量有助于進一步提高PHP面向對象程序設計的水平。本文即以實例形式描述了PHP程序設計中類常量的用法。具體如下:
類常量:類中,保存運行周期內,不變的數據。
定義:
1
2
|
const 關鍵字 const 常量名 = 常量值 |
例子如下:
1
2
3
4
5
6
7
8
|
class Student { public $stu_id ; public $stu_name ; public $stu_gender ; const GENDER_MALE= '男' ; const GENDER_FEMALE = '女' ; } |
類常量不受訪問限定修飾符的限制
訪問方法:
類::常量名
例子如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Student { public $stu_id ; public $stu_name ; public $stu_gender ; const GENDER_MALE= '男' ; const GENDER_FEMALE = '女' ; public function __construct( $id , $name , $gender = '' ) { $this ->stu_id= $id ; $this ->stu_name= $name ; $this ->gender= ( $gender == ' ' )?self::GENDER_MALE : $gender ; } } |
總結:類中可以定義的成員有:常量、靜態屬性、非靜態屬性、靜態方法、非靜態方法。
此處需要注意:
$this 表示當前對象,那么他永遠表示$this所在類的對象么?
答案是否定的!因為$this的值,不取決于$this所在的類,而是取決于$this所在方法被調用時的執行對象(執行環境)
方法的執行環境,當前方法是在哪個對象的環境下執行,該方法內的$this就表示哪個對象。