在訪問(wèn)PHP類中的成員變量或方法時(shí),如果被引用的變量或者方法被聲明成const(定義常量)或者static(聲明靜態(tài)),那么就必須使用操作符::,反之如果被引用的變量或者方法沒(méi)有被聲明成const或者static,那么就必須使用操作符->.
另外,如果從類的內(nèi)部訪問(wèn)const或者static變量或者方法,那么就必須使用自引用的self,反之如果從類的內(nèi)部訪問(wèn)不為const或者static變量或者方法,那么就必須使用自引用的$this.
$this實(shí)例代碼如下:
- <?php
- // this是指向當(dāng)前對(duì)象的指針
- class test_this{
- private $content; //定義變量
- function __construct($content){ //定義構(gòu)造函數(shù)
- $this->content= $content;
- }
- function __destruct(){}//定義析構(gòu)函數(shù)
- function printContent(){//定義打印函數(shù)
- echo $this->content.'<br />';
- }
- }
- $test=new test_this('北京歡迎你!'); //實(shí)例化對(duì)象
- $test->printContent();//北京歡迎你!
::使用方法實(shí)例代碼如下:
- //parent是指向父類的指針
- class test_parent{ //基類
- public $name; //定義姓名 父類成員需要定義為public,才能夠在繼承類中直接使用 this來(lái)調(diào)用.
- function __construct($name){
- $this->name=$name;
- }
- }
- class test_son extends test_parent{ //派生類 繼承test_parent
- public $gender;//定義性別
- public $age; //定義年齡
- function __construct($gender,$age){ //繼承類的構(gòu)造函數(shù)
- parent::__construct('nostop');//使用parent調(diào)用父類的構(gòu)造函數(shù),來(lái)進(jìn)行對(duì)父類的實(shí)例化
- $this->gender=$gender;
- $this->age=$age;
- }
- function __destruct(){}
- function print_info(){
- echo $this->name.'是個(gè)'.$this->gender.',今年'.$this->age.'歲'.'<br />';
- }
- }
- $nostop=new test_son('女性','22');//實(shí)例化test_son對(duì)象
- $nostop->print_info();//執(zhí)行輸出函數(shù) nostop是個(gè)女性,今年23歲
使用self::$name的形式.注意的是const屬性的申明格式,const PI=3.14,而不是const $PI=3.14
實(shí)例代碼如下:
- class clss_a {
- private static $name="static class_a";
- const PI=3.14;
- public $value;
- public static function getName()
- {
- return self::$name;
- }
- //這種寫(xiě)法有誤,靜態(tài)方法不能訪問(wèn)非靜態(tài)屬性
- public static function getName2()
- {
- return self::$value;
- }
- public function getPI()
- {
- return self::PI;
- }
- }
還要注意的一點(diǎn)是如果類的方法是static的,他所訪問(wèn)的屬性也必須是static的.
在類的內(nèi)部方法訪問(wèn)未聲明為const及static的屬性時(shí),使用$this->value ='class_a';的形式.
新聞熱點(diǎn)
疑難解答