php5中this_self_parent关键字用法讲解
生活随笔
收集整理的這篇文章主要介紹了
php5中this_self_parent关键字用法讲解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
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-><name )變成了print( $nameObject->name ),那么當然就輸出了"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 = ++self::$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來調用。
轉載于:https://my.oschina.net/pengting/blog/99369
總結
以上是生活随笔為你收集整理的php5中this_self_parent关键字用法讲解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Apache Zookeeper入门1
- 下一篇: 发布代码小助手V2.1发布了——Code