建構方法在物件實例化時自動呼叫,用於初始化屬性。PHP 5 支援 __construct() 與同名方法兩種形式,優先使用 __construct()。
__construct() 優先。public。<?php
class Person {
public $name; public $age;
public function __construct() { echo "我是建構方法!"; }
}
$p1 = new Person(); // 輸出:我是建構方法!
?>
$this$this 代表目前物件的參考位址。$this 即指向該物件。<?php
class Person {
public $name; public $age;
public function __construct() {
$this->name = "www.bianceng.cn";
$this->age = 10;
}
}
$p1 = new Person();
echo "$p1->name is $p1->age years old!";
?>
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
$p1 = new Person("張三", 30);