PHP關鍵字this指向當前對象指針
PHP關鍵字this是指向當前對象的指針。我們將和大家一起結合一個范例來細細研究一下PHP關鍵字this的相關用法和具體功能體現。#t#
- < ?php
- class UserName
- {
- //定義屬性
- private $name;
- //定義構造函數
- function __construct( $name )
- {
- $this->name = $name;
//這里已經使用了this指針 - }
- //析構函數
- function __destruct(){}
- //打印用戶名成員函數
- function printName()
- {
- print( $this->name );
//又使用了PHP關鍵字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-><name )變成了print( $nameObject->name ),那么當然就輸出了"heiyeluren"。
第二個實例的時候,print( $this->name )變成了print( $nameObject2->name ),于是就輸出了"PHP5"。所以說,PHP關鍵字this就是指向當前對象實例的指針,不指向任何其他對象或類。