在php中,“$this”的意思為“當前對象”,它是指向當前對象實例的指針,與連接符“->”聯合使用,專門用來完成對象內部成員之間的訪問;語法“$this -> 成員屬性;”或“$this -> 成員方法(參數列表);”。
本教程操作環境:windows7系統、PHP7.1版、DELL G3電腦
$this 的含義是表示實例化后的具體對象,即當前對象;$this就是指向當前對象實例的指針,不指向任何其他對象或類。
在 PHP 面向對象編程中,對象一旦被創建,在對象中的每個成員方法里面都會存在一個特殊的對象引用“$this
”。成員方法屬于哪個對象,“$this
”就代表哪個對象,與連接符->
聯合使用,專門用來完成對象內部成員之間的訪問。如下所示:
$this -> 成員屬性; $this -> 成員方法(參數列表);
比如在 Website 類中有一個 $name
屬性,我們可以在類中使用如下方法來訪問 $name
這個成員屬性:
$this -> name;
需要注意的是,在使用 $this
訪問某個成員屬性時,后面只需要跟屬性的名稱即可,不需要$
符號。另外,$this
只能在對象中使用,其它地方不能使用 $this
,而且不屬于對象的東西 $this
也調用不了,可以說沒有對象就沒有 $this。
【示例】使用 $this 調用類中的屬性和方法。
<?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中文網'); ?>
輸出結果:
推薦學習:《PHP視頻教程》