国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 開(kāi)發(fā) > PHP > 正文

PHP中::、->、self、$this操作符

2024-05-04 21:57:37
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

在訪問(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í)例代碼如下:

  1. <?php 
  2. // this是指向當(dāng)前對(duì)象的指針 
  3. class test_this{ 
  4.     private $content//定義變量 
  5.      
  6.     function __construct($content){ //定義構(gòu)造函數(shù) 
  7.           $this->content= $content
  8.     } 
  9.     function __destruct(){}//定義析構(gòu)函數(shù) 
  10.      
  11.     function printContent(){//定義打印函數(shù) 
  12.         echo $this->content.'<br />'
  13.     } 
  14. $test=new test_this('北京歡迎你!'); //實(shí)例化對(duì)象 
  15. $test->printContent();//北京歡迎你! 

::使用方法實(shí)例代碼如下:

  1. //parent是指向父類的指針 
  2. class test_parent{ //基類 
  3.     public $name;  //定義姓名  父類成員需要定義為public,才能夠在繼承類中直接使用 this來(lái)調(diào)用. 
  4.     function __construct($name){ 
  5.         $this->name=$name
  6.     } 
  7. class test_son extends test_parent{ //派生類  繼承test_parent 
  8.     public $gender;//定義性別 
  9.     public $age;    //定義年齡 
  10.     function __construct($gender,$age){ //繼承類的構(gòu)造函數(shù) 
  11.         parent::__construct('nostop');//使用parent調(diào)用父類的構(gòu)造函數(shù),來(lái)進(jìn)行對(duì)父類的實(shí)例化 
  12.         $this->gender=$gender
  13.         $this->age=$age
  14.     } 
  15.     function __destruct(){} 
  16.     function print_info(){ 
  17.         echo $this->name.'是個(gè)'.$this->gender.',今年'.$this->age.'歲'.'<br />'
  18.     } 
  19. $nostop=new test_son('女性','22');//實(shí)例化test_son對(duì)象 
  20. $nostop->print_info();//執(zhí)行輸出函數(shù)  nostop是個(gè)女性,今年23歲 

使用self::$name的形式.注意的是const屬性的申明格式,const PI=3.14,而不是const $PI=3.14

實(shí)例代碼如下:

  1. class clss_a { 
  2.       
  3.      private static  $name="static class_a"
  4.       
  5.      const PI=3.14; 
  6.      public $value;     
  7.           
  8.      public static function getName() 
  9.      { 
  10.         return self::$name;     
  11.      } 
  12.      //這種寫(xiě)法有誤,靜態(tài)方法不能訪問(wèn)非靜態(tài)屬性 
  13.      public static function getName2() 
  14.      { 
  15.          return self::$value
  16.      } 
  17.      public function getPI() 
  18.      { 
  19.        return self::PI;     
  20.      } 
  21.       
  22.       
  23.  } 

還要注意的一點(diǎn)是如果類的方法是static的,他所訪問(wèn)的屬性也必須是static的.

在類的內(nèi)部方法訪問(wèn)未聲明為const及static的屬性時(shí),使用$this->value ='class_a';的形式.

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 松桃| 库车县| 临沭县| 三原县| 义乌市| 六枝特区| 棋牌| 铜山县| 县级市| 宁国市| 铜鼓县| 沿河| 敖汉旗| 阜阳市| 崇州市| 昔阳县| 林州市| 甘肃省| 麻栗坡县| 襄垣县| 红桥区| 宁陕县| 临沧市| 乐业县| 绩溪县| 长治市| 奎屯市| 醴陵市| 张家界市| 二连浩特市| 樟树市| 灌南县| 临夏市| 泰宁县| 偃师市| 望奎县| 中卫市| 华蓥市| 班戈县| 仁怀市| 中山市|