首頁  >  文章  >  你知道Thinkphp5中this關鍵字的用法?

你知道Thinkphp5中this關鍵字的用法?

怪我咯
怪我咯原創
2017-06-30 09:59:072001瀏覽

PHP從5開始具備了大部分物件導向語言的特性,比PHP4多了很多物件導向的特性,在此我們主要講解三個關鍵字: this,self,parent,從字面上比較好理解,是指這,自己,父親,我們先建立幾個概念,這三個關鍵字分別是用在什麼地方呢?我們初步解釋一下,this是指向當前對象的指針(我們姑且用C裡面的指標來看吧),self是指向目前類別的指標,parent是指向父類別的指標。

下面透過實例講解

(1) this

<?php
class UserName
{
//定义属性
private $name;
//定义构造函数
function construct( $name ){
$this->name = $name; //这里已经使用了this指针
}
//析构函数
function destruct(){}
//打印用户名成员函数
function printName(){
print( $this->name ); //又使用了this指针
}
}
//实例化对象
$nameObject = new UserName( "heiyeluren" );
//执行打印
$nameObject->printName(); //输出: heiyeluren
//第二次实例化对象
$nameObject2 = new UserName( "PHP5" );
//执行打印
$nameObject2->printName(); //输出:PHP5
?>

我 們看,上面的類別分別在11行和20行使用了this指針,那麼當時this是指向誰呢?其實this是在實例化的時候來確定指向誰,例如第一次實例化物件的時候(25行),那麼當時this就是指向$nameObject物件,那麼執行18行的列印的時候就把print( $this->cbf0984c2ecd1100b3d76633da6baa6dname ),那麼當然就輸出了"heiyeluren"。第二個實例的時候,print( $this->name )變成了print( $nameObject2->name ),於是就輸出了"PHP5"。所以說,this就是指向當前物件實例的指針,不指向任何其他物件或類別。

(2)self

首先我們要明確一點,self是指向類別本身,也就是self是不指向任何已經實例化的對象,一般self使用來指向類別中的靜態變數。

<?php
class Counter
{
//定义属性,包括一个静态变量
private static $firstCount = 0;
private $lastCount;
//构造函数
function construct(){
$this->lastCount = ++selft::$firstCount; //使用self来调用静态变量,使用self调用必须使用::(域运算符号)
}
//打印最次数值
function printLastCount(){
print( $this->lastCount );
}
}
//实例化对象
$countObject = new Counter();
$countObject->printLastCount(); //输出 1
?>

我 們這裡只要注意兩個地方,第6行和第12行。我們在第二行定義了一個靜態變數$firstCount,初始值為0,那麼在12行的時候調用了這個值得,使用的是self來調用,並且中間使用"::"來連接,就是我們所謂的域運算符,那麼這時候我們呼叫的就是類別自己定義的靜態變數$frestCount,我們的靜態變數與下面物件的實例無關,它只是跟類別有關,那麼我呼叫類別本身的,那麼我們就無法使用this來引用,可以使用self來引用,因為self是指向類別本身,與任何物件實例無關。換句話說,假如我們的類別裡面靜態的成員,我們也必須使用self來呼叫。

(3)parent

我們知道parent是指向父類別的指針,一般我們使用parent來呼叫父類別的建構子。

<?php
//基类
class Animal
{
//基类的属性
public $name; //名字
//基类的构造函数
public function construct( $name ){
$this->name = $name;
}
}
//派生类
class Person extends Animal //Person类继承了Animal类
{
public $personSex; //性别
public $personAge; //年龄
//继承类的构造函数
function construct( $personSex, $personAge ){
parent::construct( "heiyeluren" ); //使用parent调用了父类的构造函数
$this->personSex = $personSex;
$this->personAge = $personAge;
}
function printPerson(){
print( $this->name. " is " .$this->personSex. ",this year " .$this->personAge );
}
}
//实例化Person对象
$personObject = new Person( "male", "21");
//执行打印
$personObject->printPerson(); //输出:heiyeluren is male,this year 21
?>

我們注意到這麼幾個細節:成員屬性都是public的,特別是父類別的,是為了供繼承類別透過this來存取。我們注意關鍵的地方,第25 行:parent:: construct( "heiyeluren" ),這時候我們就使用parent來呼叫父類別的建構子進行對父類別的初始化,因為父類別的成員都是public的,於是我們就能夠在繼承類別中直接使用this來呼叫。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn