PHP關(guān)鍵字this指向當(dāng)前對(duì)象指針
PHP關(guān)鍵字this是指向當(dāng)前對(duì)象的指針。我們將和大家一起結(jié)合一個(gè)范例來(lái)細(xì)細(xì)研究一下PHP關(guān)鍵字this的相關(guān)用法和具體功能體現(xiàn)。#t#
- < ?php
- class UserName
- {
- //定義屬性
- private $name;
- //定義構(gòu)造函數(shù)
- function __construct( $name )
- {
- $this->name = $name;
//這里已經(jīng)使用了this指針 - }
- //析構(gòu)函數(shù)
- function __destruct(){}
- //打印用戶(hù)名成員函數(shù)
- function printName()
- {
- print( $this->name );
//又使用了PHP關(guān)鍵字this指針 - }
- }
- //實(shí)例化對(duì)象
- $nameObject = new UserName
( "heiyeluren" ); - //執(zhí)行打印
- $nameObject->printName();
//輸出: heiyeluren - //第二次實(shí)例化對(duì)象
- $nameObject2 = new UserName( "PHP5" );
- //執(zhí)行打印
- $nameObject2->printName(); //輸出:PHP5
- ?>
我 們看,上面的類(lèi)分別在11行和20行使用了this指針,那么當(dāng)時(shí)this是指向誰(shuí)呢?其實(shí)this是在實(shí)例化的時(shí)候來(lái)確定指向誰(shuí),比如第一次實(shí)例化對(duì)象 的時(shí)候(25行),那么當(dāng)時(shí)this就是指向$nameObject對(duì)象,那么執(zhí)行18行的打印的時(shí)候就把print( $this-><name )變成了print( $nameObject->name ),那么當(dāng)然就輸出了"heiyeluren"。
第二個(gè)實(shí)例的時(shí)候,print( $this->name )變成了print( $nameObject2->name ),于是就輸出了"PHP5"。所以說(shuō),PHP關(guān)鍵字this就是指向當(dāng)前對(duì)象實(shí)例的指針,不指向任何其他對(duì)象或類(lèi)。