在php中,“$this”的意思為“當(dāng)前對(duì)象”,它是指向當(dāng)前對(duì)象實(shí)例的指針,與連接符“->”聯(lián)合使用,專門用來完成對(duì)象內(nèi)部成員之間的訪問;語法“$this -> 成員屬性;”或“$this -> 成員方法(參數(shù)列表);”。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
$this 的含義是表示實(shí)例化后的具體對(duì)象,即當(dāng)前對(duì)象;$this就是指向當(dāng)前對(duì)象實(shí)例的指針,不指向任何其他對(duì)象或類。
在 PHP 面向?qū)ο缶幊讨?,?duì)象一旦被創(chuàng)建,在對(duì)象中的每個(gè)成員方法里面都會(huì)存在一個(gè)特殊的對(duì)象引用“$this
”。成員方法屬于哪個(gè)對(duì)象,“$this
”就代表哪個(gè)對(duì)象,與連接符->
聯(lián)合使用,專門用來完成對(duì)象內(nèi)部成員之間的訪問。如下所示:
$this -> 成員屬性; $this -> 成員方法(參數(shù)列表);
比如在 Website 類中有一個(gè) $name
屬性,我們可以在類中使用如下方法來訪問 $name
這個(gè)成員屬性:
$this -> name;
需要注意的是,在使用 $this
訪問某個(gè)成員屬性時(shí),后面只需要跟屬性的名稱即可,不需要$
符號(hào)。另外,$this
只能在對(duì)象中使用,其它地方不能使用 $this
,而且不屬于對(duì)象的東西 $this
也調(diào)用不了,可以說沒有對(duì)象就沒有 $this。
【示例】使用 $this 調(diào)用類中的屬性和方法。
<?php header("Content-type:text/html;charset=utf-8"); class Website { public $name; public function __construct($name) { $this -> name = $name; $this -> name(); } public function name() { echo $this -> name . '<br>'; $this -> url(); } public function url() { echo 'https://www.php.cn/<br>'; $this -> title(); } public function title() { echo 'PHP入門教程<br>'; } } $object = new Website('PHP中文網(wǎng)'); ?>
輸出結(jié)果:
推薦學(xué)習(xí):《PHP視頻教程》