標籤:使用 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這幾個關鍵字使用方法