另外,如果從類的內部訪問const或者static變數或者方法,那麼就必須使用自引用的self,反之如果從類的內部訪問不為const或者static變數或者方法,那麼就必須使用自引用的$this。
$this執行個體
| 代碼如下 |
複製代碼 |
<?php // this是指向當前對象的指標 class test_this{ private $content; //定義變數 function __construct($content){ //定義建構函式 $this->content= $content; } function __destruct(){}//定義解構函式 function printContent(){//定義列印函數 echo $this->content.'<br />'; } } $test=new test_this('北京歡迎你!'); //執行個體化對象 $test->printContent();//北京歡迎你! |
::使用方法
| 代碼如下 |
複製代碼 |
//parent是指向父類的指標 class test_parent{ //基類 public $name; //定義姓名 父類成員需要定義為public,才能夠在繼承類中直接使用 this來調用。 function __construct($name){ $this->name=$name; } } class test_son extends test_parent{ //衍生類別 繼承test_parent public $gender;//定義性別 public $age; //定義年齡 function __construct($gender,$age){ //繼承類的建構函式 parent::__construct('nostop');//使用parent調用父類的建構函式,來進行對父類的執行個體化 $this->gender=$gender; $this->age=$age; } function __destruct(){} function print_info(){ echo $this->name.'是個'.$this->gender.',今年'.$this->age.'歲'.'<br />'; } } $nostop=new test_son('女性','22');//執行個體化test_son對象 $nostop->print_info();//執行輸出函數 nostop是個女性,今年23歲 |
使用self::$name的形式。注意的是const屬性的申明格式,const PI=3.14,而不是const $PI=3.14
| 代碼如下 |
複製代碼 |
class clss_a { private static $name="static class_a"; const PI=3.14; public $value; public static function getName() { return self::$name; } //這種寫法有誤,靜態方法不能訪問非靜態屬性 public static function getName2() { return self::$value; } public function getPI() { return self::PI; } } |
還要注意的一點是如果類的方法是static的,他所訪問的屬性也必須是static的。
在類的內部方法訪問未聲明為const及static的屬性時,使用$this->value ='class_a';的形式。