php類中的$this,static,const,self這幾個關鍵字使用方法

來源:互聯網
上載者:User

標籤:使用   name   pre   highlight   常見   run   cal   color   obj   

本篇文章主要分享一下關於php類中的$this,static,final,const,self這幾個關鍵字使用方法

$this

$this表示當前執行個體,在類的內部方法訪問未聲明為const及static的屬性時,使用$this->value=‘phpernote‘;的形式。常見用法如:$this->屬性,$this->方法

<?php  /**  * 有關人類  */  class Person  {        private $name=‘張三‘;    public  $sex;    public function run(){      return $this->name.‘能跑‘;    }    public function length(){      echo $this->run().‘800米‘;    }  }  $person=new Person();  $person->length();?>

static

聲明及調用靜態變數如下:

  <?php  /**  * 樣本  */  class Person  {    static  $sex=1;    public  $name=‘張三‘;    static function qianDao(){      return self::$sex++;    }    static function printQianDao(){      echo self::qianDao();    }    static function printQianDao2(){      echo $this->qianDao();    }    static function printQianDao3(){      echo $this->name;    }    public function printQianDao4(){      echo $this->name;    }  }  $person=new Person();  $person->printQianDao();//輸出1  Person::printQianDao(); //輸出2  $person->printQianDao2();//報錯:Using $this when not in object context  $person->printQianDao3();//報錯:Using $this when not in object context  $person->printQianDao4();//輸出“張三”;  Person::printQianDao4(); //報錯1:Non-static method Person::printQianDao4() should not be called statically,報錯2:Using $this when not in object context?>

  

注意事項:

  1.在靜態方法內部,不能使用$this(即在靜態方法內部只能調用靜態成員);

  2.調用靜態成員的方法只能是self::方法名或者parent::方法名或者類名::方法名

  3.在類的外部,調用靜態方法時,可以不用執行個體化,直接類名::方法名

  4.靜態方法執行之後變數的值不會丟失,只會初始化一次,這個值對所有執行個體都是有效

const

定義及調用類的常量如下:

  <?php  /**  * 樣本  */  class Person  {    const PI=1;    static function getPi(){      return self::PI;    }    static function printPi(){      echo self::getPi();    }  }  Person::printPi();?> 

 

注意:調用類的成員是self::PI,而不是self::$PI

self

self表示類本身,指向當前的類。通常用來訪問類的靜態成員、方法和常量。

 

php類中的$this,static,const,self這幾個關鍵字使用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.