PHP5中為解決變量的命名沖突和不確定性問題,引入關(guān)鍵字“$this”代表其所在當(dāng)前對(duì)象。
$this在構(gòu)造函數(shù)中指該構(gòu)造函數(shù)所創(chuàng)建的新對(duì)象。
在類中使用當(dāng)前對(duì)象的屬性和方法,必須使用$this->取值。
方法內(nèi)的局部變量,不屬于對(duì)象,不使用$this關(guān)鍵字取值。
局部變量和全局變量與 $this 關(guān)鍵字,使用當(dāng)前對(duì)象的屬性必須使用$this關(guān)鍵字。局部變量的只在當(dāng)前對(duì)象的方法內(nèi)有效,所以直接使用。
注意:局部變量和屬性可以同名,但用法不一樣。在使用中,要盡量避免這樣使用,以免混淆。
<?php
class A
{
private $a = 99;
//這里寫一個(gè)打印參數(shù)的方法
public function printInt($a) {
echo "/$a是傳遞的參數(shù) $a ";
echo "<br />";
echo "/$this->a 是屬性 $this->a";
}
}
$a = new A(); //這里的$a可不是類中的任何變量
$a->printInt(88);
?>
用$this調(diào)用對(duì)象中的其它方法
<?php
class Math
{
//兩個(gè)數(shù)值比較大小
public function Max($a, $b) {
return $a > $b ? $a : $b;
}
//三個(gè)數(shù)值比較大小
public function Max3($a, $b, $c) {
$a = $this->Max($a, $b); //調(diào)用類中的其它方法
return $this->Max($a, $c);
}
}
$math = new Math();
echo "最大值是 " . $math->Max3(99, 100, 88);
?>
使用$this調(diào)用構(gòu)造函數(shù)
調(diào)用構(gòu)造函數(shù)和析構(gòu)函數(shù)的方法一致。
<?php
class A
{
private $a = 0;
public function __construct() {
$this->a = $this->a + 1;
}
public function doSomeThing() {
$this->__construct();
return $this->a;
}
}
$a = new A(); // 這里的$a 可不是類中的任何一個(gè)變量了
echo "現(xiàn)在 /$a 的值是" . $a->doSomeThing();
?>
$this 到底指的什么?
$this 就是指當(dāng)前對(duì)象,我們甚至可以返回這個(gè)對(duì)象使用 $this。
<?php
class A
{
public function getASelf() {
return $this;
}
public function __toString() {
return "這是類A的實(shí)例";
}
}
$a = new A(); //創(chuàng)建A的實(shí)例
$b = $a->getASelf(); //調(diào)用方法返回當(dāng)前實(shí)例
echo $a; //打印對(duì)象會(huì)調(diào)用它的__toString方法
?>
通過 $this 傳遞對(duì)象
在這個(gè)例子中,我們寫一個(gè)根據(jù)不同的年齡發(fā)不同工資的類。我們?cè)O(shè)置處理年齡和工資的業(yè)務(wù)模型為一個(gè)獨(dú)立的類。
<?php
class User
{
private $age ;
private $sal ;
private $payoff ; //聲明全局屬性
//構(gòu)造函數(shù),中創(chuàng)建Payoff的對(duì)象
public function __construct() {
$this->payoff = new Payoff();
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
$this->age = $age;
}
// 獲得工資
public function getSal() {
$this->sal = $this->payoff->figure($this);
return $this->sal;
}
}
//這是對(duì)應(yīng)工資與年齡關(guān)系的類.
class Payoff
{
public function figure($a) {
$sal =0;
$age = $a->getAge();
if ($age > 80 || $age < 16 ) {
$sal = 0;
} elseif ($age > 50) {
$sal = 1000;
} else {
$sal = 800;
}
return $sal;
}
}
//實(shí)例化User
$user = new User();
$user->setAge(55);
echo $user->getAge() . " age, his sal is " . $user->getSal();
echo "<br />";
$user->setAge(20);
echo $user->getAge() . " age, his sal is " . $user->getSal();
echo "<br />";
$user->setAge(-20);
echo $user->getAge() . " age, his sal is " . $user->getSal();
echo "<br />";
$user->setAge(150);
echo $user->getAge() . " age, his sal is " . $user->getSal();
?>