代表目前物件實例,僅能在非靜態方法內使用。相當於「我」。
class Person {
public $name;
public function say() {
echo "我是 {$this->name}<br>";
}
}
$p = new Person(); $p->name = "張三";
$p->say(); // 我是張三
__construct(),PHP 4 使用類別同名方法class Person {
public $name, $age, $gender;
// PHP 5+ 風格
public function __construct($name, $age, $gender) {
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
public function introduce() {
echo "我是 {$this->name},{$this->age} 歲,{$this->gender}性<br>";
}
}
$p1 = new Person("張三", 90, "男");
$p2 = new Person("李四", 23, "女");
$p1->introduce(); $p2->introduce();
unset()、超出作用域)class Person {
public $name;
public function __construct($name) {
$this->name = $name;
echo "{$name} 誕生了<br>";
}
public function __destruct() {
echo "{$this->name} 說再見<br>";
}
}
$p1 = new Person("張三");
$p2 = new Person("李四");
$p3 = new Person("王五");
echo "腳本即將結束<br>";
// 輸出順序:
// 張三 誕生了
// 李四 誕生了
// 王五 誕生了
// 腳本即將結束
// 王五 說再見
// 李四 說再見
// 張三 說再見 (反序銷毀)
| 版本 | 建構子名稱 | 備註 |
|---|---|---|
| PHP 4 | 類別同名 function Person() | 已淘汰 |
| PHP 5+ | __construct() | 標準,支援繼承鏈自動呼叫父建構子 |